0

I'm working on web app that require a login page, everything work until I try to convert to PDO and use prepared query here is my code:

$req=$idconnex->prepare("SELECT * FROM `enseignant` WHERE ens_cin=:cin AND ens_pass=:pass");
$req->bindParam(':cin',$_GET["login"]);
$req->bindParam(':pass',$_GET["password"]);
$res=$idconnex->exec($req);
if(!empty($res) AND $res->rowCount==1)          
    {echo 'SUCCESS';}
else
    {echo 'FAIL';}

A warning appearsy:

Warning: PDO::exec() expects parameter 1 to be string, object given in...

and it return FAIL as result even I insert correct param!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Malek Boubakri
  • 820
  • 2
  • 17
  • 36

2 Answers2

5

When you prepare a statement, you need execute instead of exec and you need to use the object you set when you prepared it:

$req=$idconnex->prepare("SELECT * FROM `enseignant` WHERE ens_cin=:cin AND ens_pass=:pass");
$req->bindParam(':cin',$_GET["login"]);
$req->bindParam(':pass',$_GET["password"]);
$req->execute();

Also note that rowCount() is a method, not a property, and you cannot rely on its value when you use a SELECT query. See the manual page about rowCount() for more information.

Furthermore you should not use GET but POST when you send information like passwords and you should use a salted hash for your password, never a plain-text password. See Secure hash and salt for PHP passwords for more details.

Community
  • 1
  • 1
jeroen
  • 91,079
  • 21
  • 114
  • 132
2

Add this to jeroen's answer

$status = $req->fetch(\PDO::FETCH_ASSOC);
if($status)          
{echo 'SUCCESS';}
else
{echo 'FAIL';}

The $req->fetch(\PDO::FETCH_ASSOC); was actually asking for the result of the query. You can see what it contains by var_dump($status). It will return an associative array if a match is found or empty if no match is found.

PHP will evaluate non-empty variable as boolean true and empty,null,array with zero elements.. as boolean false. if($status) is almost the same as if($status == true). You can find this in the PHP manual.

frz3993
  • 1,595
  • 11
  • 13
  • Added some explanation to the answer. You do understand what jeroen wrote right ? If you want to put your code into production you will need to listen to his advice. :) – frz3993 Apr 18 '15 at 21:20