phppdoprepared-statementrowcount

How to get number of rows with fetchColumn and bindParam


Why does this not work

   $sth = $pdo->prepare("SELECT * FROM tempusers WHERE tempusers.username = :username AND   tempuser.email = :email AND password = :password");

   $sth->bindParam(':username', $register_data['username'], PDO::PARAM_STR);
   $sth->bindParam(':email', $register_data['email'], PDO::PARAM_STR);
   $sth->bindParam(':password', $register_data['password'], PDO::PARAM_STR);
   $sth->execute();
  if($sth->fetchColumn() > 0) {
      echo 'yes';
  }else{
      echo 'no';
  }

And then when I run this code it works

   $sth = $pdo->prepare("SELECT * FROM tempusers WHERE tempusers.username = :username");
   $sth->bindParam(':username', $register_data['username'], PDO::PARAM_STR);
   $sth->execute();
  if($sth->fetchColumn() > 0) {
      echo 'yes';
  }else{
      echo 'no';
  }

When I try to use more then on bindParam value the code crashes. Why can't have more the one value to check against?


Solution

  • To get number of rows with fetchColumn, you have to select this number with your query

    So, instead of

    SELECT * FROM
    

    you have to make it

    SELECT count(*) FROM
    

    and you will have that number.

    bindParam have to be used as usual, the same way you did it before.
    However, you have to avoid typos and the like mistakes in your code.
    And of course you have to set up proper error reporting to make yourself be able to spot all the errors.

    Why does this not work

    Always connect to PDO as described in the tag wiki
    and you will know.