Jump to content

Improving a PDO login script.


sepoto

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 comment
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 comment
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 comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...