$db->query()
returns either 0
or a mysqli_result
object. That code with a DESCRIBE
query looks like it's intended to check if a particular table exists. If the table doesn't exist, the DESCRIBE
query will fail and $db->query()
will return 0
. If the table does exist, the query will succeed and $db->query()
will return a mysqli_result
object.
Using if($data == 0)
to check whether the query failed will cause PHP to try to cast the mysqli_result
object to an integer so it can compare it to the integer 0
. This is not possible. Your code will function correctly (since not-a-readable-integer-value
is not equal to 0
) but it will throw a notice informing you of the problem.
You probably always got this notice, but had error messaging suppressed so you just didn't see it.
To avoid the notice and still have the check working properly, you need to stop PHP from trying to cast the object to an integer. You can do that with an ===
check, which is more strict:
function check_database($table_name) {
$db = Database::obtain();
$sql = "DESCRIBE ".$table_name;
$data = $db->query($sql);
if($data === 0) {
return false;
} else
return true;
}
With ===
, the first check PHP will perform is "are both of these things of the same type", basically "are they both integers" or "are they both mysqli_result objects" (depending on the left side of the comparison, $data
, so it depends on if the query succeeded or not). Only if both are integers will it check if both are 0
. If they're of different types, it will immediately pass to the else
block and your code will still work as intended.