Reputation: 13176
I've used PDO in my PHP application. But I have problem with fetch()
function. Whenever I count the result of fetch()
, it tells me there is something in resultset. But when I want to show them, it has nothing to show.
try
{
$sql = "SELECT id,salt FROM tbl_admin WHERE username = ? AND password = ? LIMIT 1";
$q = $db->prepare($sql);
$q->execute(array($username,$password));
$rows = $q->columnCount();
if ($rows > 0)
{
$r = $q->fetch(PDO::FETCH_BOTH);
echo(count($r).'<br />'); // Prints 1
print_r($r); // Nothing to print ...
die();
}
else
{
die('error');
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
May you help me please?
Upvotes: 1
Views: 232
Reputation: 12889
You're counting the number of columns, not the number of rows.
$rows = $q->columnCount();
This should be
$rows = $q->rowCount();
rowCount
is for UPDATE, INSERT, or DELETE queries. So that isn't the problem here.
Firstly should also be checking if $q->execute
returns true or false.
Secondly you should be checking if $q->fetch
returns true or false.
Given your code
$r = $q->fetch(PDO::FETCH_BOTH);
echo(count($r).'<br />'); // Prints 1
Try the following.
echo(count(false));
You'll notice that this also outputs 1.
So the solution is, that you need to check the return value of $q->fetch
before assuming it returned a valid row.
Upvotes: 3