2

I have some code that currently works but I need to turn it into a function in my users class. This is the SQL which I want to turn in to a function

 if(isset($_POST['teams'])){
        $stmt = $DB_con->prepare("UPDATE users SET team_id= '$playerteam' WHERE user_id = $user_id ");
             $stmt->execute();
        }
         if(isset($_POST['leaveteam'])){
        $stmt = $DB_con->prepare("UPDATE users SET team_id= 0 WHERE user_id = $user_id ");
             $stmt->execute();
        }
    $stmt = $DB_con->prepare("SELECT * FROM teams
    INNER JOIN users
    ON teams.id=users.team_id
    ORDER BY team_name ASC");
    $stmt->execute();
    $teamRow=$stmt->fetchall(PDO::FETCH_ASSOC);?>

I tried this but I could not get the function to update the team_id

   public function joinTeam($playerteam)
   {
        if(isset($_POST['teams'])){
    $stmt = $DB_con->prepare("UPDATE users SET team_id= '$playerteam' WHERE user_id = $user_id ");
         $stmt->execute();
   }

Would anyone be able to help me turn this sql in to a function, thanks.

Dannad
  • 151
  • 1
  • 10
  • 2
    a) There is no $user_id within the function's scope. Where does it come from? b) you're already using a prepared statement, why aren't you using parameters instead of mixing in the possibly insecure payload? – VolkerK Dec 22 '15 at 23:52
  • If you really want to use a function without sending the variables through the parameters, you could take a look at using http://php.net/manual/en/reserved.variables.globals.php `$_GLOBAL` variables. Probably not advised though. – Matt Dec 22 '15 at 23:53

1 Answers1

0

$user_id and $DB are not seen inside the function. In PHP only variables that were declared inside the function are visible in it, unless they are explicitly declared global. You have two ways to address it:

  1. Pass $user_id and $DB as arguments to your function:
public function joinTeam($DB, $user_id, $playerteam)
{
    ...
  1. Make your user_id and DB global. Beware that this is considered to be bad practice (and it would also be inconsistent with the fact that you pass playerteam as an argument):
public function joinTeam($playerteam)
{
    global $user_id;
    global $DB;
    ...

Also note that the way you execute your queries is prone to sql-injections. See this stackoverflow answer for details and how to avoid it: How can prepared statements protect from SQL injection attacks?

Community
  • 1
  • 1
Ishamael
  • 12,583
  • 4
  • 34
  • 52
  • How would I call the function? I have update the function with your help and have added the onclick call to my submit button, but it's still not working input type="submit" value="Join" onclick="joinTeam()" /> – Dannad Dec 23 '15 at 00:19
  • You can't call a php function from javascript. You need to send an explicit request to the server, either via submitting a form or using Ajax. More details here: http://stackoverflow.com/questions/15757750/php-function-call-using-javascript – Ishamael Dec 23 '15 at 00:24