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?
You’re counting the number of columns, not the number of rows.
$rows = $q->columnCount();This should be
$rows = $q->rowCount();That said,
rowCountis for UPDATE, INSERT, or DELETE queries. So that isn’t the problem here.Firstly should also be checking if
$q->executereturns true or false.Secondly you should be checking if
$q->fetchreturns true or false.Given your code
Try the following.
You’ll notice that this also outputs 1.
So the solution is, that you need to check the return value of
$q->fetchbefore assuming it returned a valid row.