For some reason the following code always returns true, no matter what the parameter is and what is actually inside of the SQL row. It also throws an error "Notice: Undefined offset: 0 in C:\wamp\www\Social Networking\INC\login.inc on line 7" but I do not see what is wrong:
<?php
function checkAccount($username, $password){
include("INC/dbconnect.inc");/*"INC/dbconnect.inc" is <?php $pdo = new PDO("mysql:host=localhost;dbname=socialnetwork","user","123"); ?>*/
$select = $pdo->prepare("SELECT id,password FROM users WHERE user_username = :username");
$select->execute(array(':username'=>$username));
$q_rows = $select->fetchAll();
if($q_rows[0][0]/*the ID of the user, it should always be greater than 1, if not then the username does not exist*/ > 0 && $q_rows[0][0] != null){
if($q_rows[0][1]/*the password of the user*/ == $password)
return true;
else
return false;
}
else
return false;
$pdo=null;
} ?>
Can someone please tell me what is wrong? I have commented inside of the code the problems I am experiencing, and I have tried normal $select->fetch()
instead of $select->fetchAll()
to no avail. I have read up on PDO before posting this (http://php.net/manual/en/pdostatement.fetchall.php). Here is the rest of my file http://pastebin.com/YCkrRivs, thanks.
If the database returns no rows, then there will be no entry $q_rows[0]
. Hence, undefined offset 0 as you are trying to retrieve a row in array that doesn't exist. Your 'ID' not > 0 for non-existent user is not a correct summary.
Sample return looks like this (if you print_r()'d it)
User present:
$q_rows = Array (
[0] => Array (
[id] => 1,
[password] => 'dno23n3io3'
)
)
No user present:
$q_rows = Array (
)
You should do:
if(size($q_rows) > 0) {
//Handle user present
} else {
//Handle no user present
}
You don't need to use fetchAll
, just use fetch
:
$q_row = $select->fetch();
if ($q_row) {
// do your logic ...
}
And you are returning strings "true"/"false"
, not the boolean, you should use true/false
instead.
More simple, you could just do like below:
$q_row = $select->fetch();
return $q_row && $q_row[0] > 0 && $q_row[1] === $password;