I came across the following in some old PHP code that I have to work on. My question is, are both those Ifs required? In other words, if a result is returned it must have returned greater than zero records, right? And the converse - meaning if $result is False, can I assume that no records have been found?
$sql = "SELECT * FROM houses WHERE ownerphone=$pn";
$result = $conn->query($sql);
if ($result) {
$count = $result->num_rows;
if ($count > 0){
....Stuff happens here...
} else {
...What happens here?...
}
} else {
...Other Stuff happens here
}
Yes, both are required.
if a result is returned it must have returned greater than zero records, right?
Wrong.
If you don't get a result then you got an error and you won't have an object to read the number of results back from.
You can get zero rows back from a successful request.
if $result is False, can I assume that no records have been found?
Well, yes. Sort of. That's why the if
statement stops you checking to see if there are a number of rows if the result is False.
… but not getting rows back because there was an error is different to not getting rows back because there were none to find.
No, you can't assume this. $conn->query()
returns false
if there's an error trying to perform a query. A SELECT
query that doesn't match any rows is not an error.
Errors include incorrect syntax in the query or problems communicating with the database server.
From the docs;
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
This means that it will bascically never return null
. The first check (if ( $result )
is just to make sure all went well, and you got some kind of a response from the database. The second one is to count your rows; getting a result doesn't imply your query actually returns data, because maybe you're searching for stuff that is just not there.