Mike Perrenoud
Mike Perrenoud

Reputation: 67898

How can I simply determine if there is (not) a result from PDOStatement fetch?

Consider the following code:

$conn = new PDO("connection string", "user name", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT `id` FROM `users` WHERE `displayname` = :displayname";
$parms = array(':displayname' => 'Test');
$stmt = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$stmt->execute($parms);

$res = $stmt->fetch();
echo $res == null;

and more specifically consider this line: echo ($res == null);

If there is no row in the database that matches the echo displays a value of 1 -as expected -because the $res is in fact null. However, if there is a result returned from $stmt->fetch(); the echo produces nothing. But, I would have expected it to have produced a 0 because the value of $res is an array.

How can I consistently and concisely compare the result to simply determine if there was a result or not?

Upvotes: 0

Views: 123

Answers (1)

Corbin
Corbin

Reputation: 33437

When there's no result, it doesn't return null. It returns false (well, assuming PDO::FETCH_BOTH -- to see a full list, read the doc). Also, false casted to a string is an empty string. That's why you're not getting any output.

echo false; //Outputs nothing

$s = (string) false;
var_dump($s === ""); //true 

As for determining whether or not you have a result, you can just do a simple implicit check:

$res = $stmt->fetch();
if ($res) { 
    echo 'Got a row!';
} else {
    echo 'No row :(';
}

This works because of a few implicit casts. Consider what fetch is going to return: either a non-empty array, or false. (bool) $arr === true only if count($arr) > 0. From here, you should be able to see why this works.

(Note: in theory, the result set could indeed be an empty row. This would cause fetch to return an emtpy array. That would break the implicit comparison as it would then be considered false. I can't imagine this would actually ever happen though. I can't think of a statement that would return a result set with a row that has no columns.)

Upvotes: 2

Related Questions