6
votes

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?
3

3 Answers

5
votes

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.

2
votes

As long as you are working with mysql, rowCount will provide you the number in the result set without having to do another query. Other databases may not support rowCount accurately, so you'd have to do a seperate select count(*) ... query first.

As for whether you only get true or false on an execute, that is absolutely going to be true, even for queries that return no rows. This is because in relational theory, an empty result set is completely valid, and a select with no rows is not an error.

-3
votes

Use exec();

From the PHP manual:

PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.

http://php.net/manual/en/pdo.exec.php