-4

Am getting error PHP Notice: Object of class mysqli_result could not be converted to int after having to upgrade old php app to latest PHP and mySQL and cant figure out the issue is on line 512 which is the if statement below. I am using a MySqli wrapper class > https://www.ricocheting.com/static/code/php/mysql-v3.5/Database.singleton.txt

    function check_database($table_name) {
    $db = Database::obtain();
    $sql = "DESCRIBE ".$table_name;
    $data = $db->query($sql);
    if($data == 0) {
        return false;
    } else
        return true;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Please check https://stackoverflow.com/questions/21722375/object-of-class-mysqli-result-could-not-be-converted-to-string-in – Progman May 02 '20 at 14:08
  • Using `==` will attempt to cast `$data` to an integer to compare its value to `0` like you're asking. This is failing, since `$data` is a `mysqli_result` object. Use `===` instead to perform a typesafe comparison. See [this question](https://stackoverflow.com/q/80646/1941241) for more information. – rickdenhaan May 02 '20 at 14:15

1 Answers1

-1

$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.

rickdenhaan
  • 10,857
  • 28
  • 37