Pdo issue checking string


#1

Morning,

Im getting white out when it comes to the block of code below.
I have echo'd out $username and password and they are fine, they are passed along to that bit of code no problem

$qry = $conn->prepare("SELECT * FROM UserAdmin WHERE Username=:username AND Password=:password");
$qry->bindParam(':username',$username);
$qry->bindParam(':password',$password);
$qry->execute();

if($qry->fetchColumn() > 0) {
while ($member = $qry->fetch()) {
$_SESSION['SESS_MEMBER_ID'] = $member['ID'];
$_SESSION['SESS_FIRST_NAME'] = $member['Username'];
$_SESSION['SESS_LAST_NAME'] = $member['Password'];

session_write_close();
header("location: http://www.mysite.co.uk/new/admin/index4.php"); }
}else {
$errmsg_arr[] = 'user name and password not found';
$errflag = true;
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: http://www.mysite.co.uk/admin/index.php");
exit();
}}

Its the if($gry) bit I think

I'm not sure what to do


#2

is this below the correct way forward, it seems to have worked, but sometimes im good at fudging things.

if(!empty($qry)) {
while ($member = $qry->fetch()) {

#3

I'd use

if ($qry->rowCount() > 0) {

In your original code, the first call to fetchColumn() gets the first (by default) column from the first row (but forgets all the other columns that might have been returned in that row). As with most username / password queries, though, you probably only have one record that matches if your user registration code isn't awful. So when you call the second fetch() there isn't another row to retrieve, but your code doesn't deal with that scenario.

You also might want to consider the way that you store and handle passwords, if you haven't seen it elsewhere there is a password_hash function to provide decent encoding of passwords. Instead of a query to retrieve a record based on both username and password, you retrieve based on the username (which is presumably still unique) and then call password_verify() to compare the typed-in password to the hashed version (which is what you store in the database).


#4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.