Forum Moderators: coopster

Message Too Old, No Replies

Checking if mysqli result exists before using it

         

csdude55

6:00 pm on Sep 18, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



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.

csdude55

6:31 pm on Sep 18, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Well, I guess one option would be to create another function in the existing variables script:

function num_rows($text=false) {
global $dbh;
return $text ? mysqli_num_rows($text) : 0;
}


Then I can modify every page to just use if (num_rows($result)) { ... }. That's less code, and better if I change from MySQLi in the future, but it would probably process a smidge slower...