Jump to content

Improving a PDO login script.

Recommended Posts

<?phprequire_once("php.securelogin/securelogin.php");try{$dbh = new PDO('mysql:host=localhost;dbname=timesheets', $dbuser, $dbpassword);$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e){exit($e->getMessage());}$stmt = $dbh->prepare("SELECT email,password FROM users where email = ? and password=PASSWORD(?)");if ($stmt->execute(array($_POST['email'],$_POST['password']))) {while ($row = $stmt->fetch()) {  print_r($row);}}?>

At this point if I enter a valid email and password that is in the users table the row is printed to the browser window. What I can't seem to figure out is how to handle the condition where a row is not found in the users table at which point I would like to do a header("location: index.loginfailed.php");. I have tried all different ways I can think of of detecting the condition of a row not being found but I can not seem to figure how how to do that yet. I also tried putting the $dbh->prepare code into try and catch braces looking for a PDOException but it appears that nothing is thrown if the users row is not found. Does anyone know how to do this?

Link to post
Share on other sites

I came up with this which accomplishes the goal but I'm still not sure if this is the best way...

if ($stmt->execute(array($_POST['email'],$_POST['password']))) {$count = $stmt->rowCount();if($count > 0){  header("location: main1.php");}else{  header("location: index.loginfailed.php");}}

Link to post
Share on other sites

PDOstatement::rowCount() should be used with only DML statements like INSERT,UPDATE,DELETE. Behaviour of SELECT is not same for all database driver, thus use of it for this purpose, is discouraged. You can check return value of fetch() to determine if it is returning any row or not. it should return false when there is no row. in your select statement you dont even need a loop, as there should only one password username combo. if you use fetchAll() you can use count() to determine the element number it found in database

Edited by birbal
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...