Search code examples
phppdoexecute

Detect if PDO->execute returns a row/record?


code example;

$stmt = $db->prepare('SELECT u.username, u.display_name FROM users u WHERE u.id = :userId');
$stmt->bindValue(':userId', 10);
$stmt->execute();

Using prepare -> execute. If your sure the query will return max 1 row; is there a simple way to see if query did return a row? I see everyone validating on 'rowCount', but isn't there a cleaner way?

this article: http://www.christiansouth.com/php/pdo-getting-started-part-2-pdostatement/ states;

TRUE if the query was successful FALSE if it wasn’t. The stumble here is it will ONLY return FALSE if the SQL has an error. So if the SQL is valid but return no rowset you will still get a TRUE return value.

Is this statement correct? Because php.net only talks about:

Returns TRUE on success or FALSE on failure.

So, rapping up the questions again:

  • Is it true you can't validate if a row was returned using $stmt (in above example) as a boolean?
  • Is there any solution to this that looks cleaner then 'rowCount' rapped in an if?

Solution

  • Use the result-set (i.e. fetch): was there a row or not?

    A result-set with 0 records is still perfectly valid in terms of "did it work" and is why TRUE is returned on every valid query execute'ed. In this case FALSE should be treated only as an exception condition.

    On the other hand, the result from (the first) fetch - combined with the knowledge that the query will only return 0..1 rows - can be used to determine if there was a single row fetched. Since this is the "standard" way to access the data for such a query, there is no need to perform an additional check.