note 114824 added to pdostatement.rowcount

From: Date: Thu, 10 Apr 2014 11:09:22 +0000
Subject: note 114824 added to pdostatement.rowcount
Groups: php.notes 
Request: Send a blank email to php-notes+get-199239@lists.php.net to get a copy of this message
Yet another workaround to return the row count inside only ONE select (see limitations below!): $sth = $dbh->prepare("SELECT *,count(*) AS howmany FROM users WHERE email=:email and password=:pass"); #var placeholders $sth->execute(array(':email'=>$email, ':pass'=>$pass)); #var binding $row = $sth->fetch(); #get one row (it'll always be one and only one!!!) if ($row['howmany'] == 1){ #we have a match and only one! cool! echo $row['email'], $row['name'], $row['phone'], ... ; } elseif ($row['howmany']>1) { #more than one row returned #one programmer should be fired 'cause he's not checking for #for existing emails, before creating a new user ... # treat this exception somehow or simply skip this branch, # if you're sure it won't happen in your table } else { #no match in the table ($row['howmany'] == 0) echo "Email/pass didn't match the ones in the database!"; } Advantages: - only one select statement is executed, no two steps needed! - it checks if one row exists in the table or not, according to the WHERE clause. - it returns all (or only a selection of) fields for that one row, if exists. Disadvantages: - it doesn't return row fields reliable if more than one row found. If more than one row responds to the SELECT query, the query returns still only one row and you don't know which one exactly . Maybe using a SORT BY, would make it a bit more predictible (as in: "if more than one users found, return the last user added in the table") but it's more a matter of good design of the program that fills in the table initially. Uses: - It is perfect for checking if a user/pass pair is present in a users table and to return the other fields of the user (like name, phone, whatever) if user was found. ---- Server IP: 72.52.91.14 Probable Submitter: 86.59.192.87 ---- Manual Page -- http://php.net/manual/en/pdostatement.rowcount.php Edit -- https://master.php.net/note/edit/114824 Del: integrated -- https://master.php.net/note/delete/114824/integrated Del: useless -- https://master.php.net/note/delete/114824/useless Del: bad code -- https://master.php.net/note/delete/114824/bad+code Del: spam -- https://master.php.net/note/delete/114824/spam Del: non-english -- https://master.php.net/note/delete/114824/non-english Del: in docs -- https://master.php.net/note/delete/114824/in+docs Del: other reasons-- https://master.php.net/note/delete/114824 Reject -- https://master.php.net/note/reject/114824 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199239) next »