Historically, I've used code like this:
$result = query('select * from table');
if ($result && mysqli_num_rows($result)) {
...
}
// this is in a variables script that I load on every page
function query($text) {
global $dbh;
return mysqli_query($dbh, $text);
}
I used to see warnings related to mysqli_num_rows() in my log from where the query failed (probably from bots), so I started testing that $result was true before doing anything else.
I recently learned that
mysqli_free_result($result)/ can speed my pages up a few microseconds. As I'm going through everything and adding that everywhere, I'm curious if I can make the above code a little shorter? That should also help result in a slightly faster page load.
What's the "best" tried-and-true method here? With the primary goal being speed to process, and secondary goal being less code.
I'm pretty sure that this works, but it's longer than the original so it defeats the purpose:
if ($result ? mysqli_num_rows($result) : 0) {
...
}
But knowing that it works, am I right that this is the same thing?
if (mysqli_num_rows($result) ? 0) {
...
}
I don't suppose there's a way to modify query() to make it return something mysqli_num_rows would return as 0 if the query fails? That would be the best solution, since it's in a function that I could modify once and "fix" every page at once.