1

I'm creating quite big import script. I want to see any problematic (unexecuted) SQL queries. I have problem with catching wrong SQL queries with try-catch PHP block.

I have a query:

SELECT id FROM tag WHERE name IN ()

Of course there is an error in it so I want to print queries like that with this code:

$sql = "SELECT id FROM tag WHERE name ".$tagsSql."";

try
{
    $query = mysqli_query($this->mysqli, $sql);
    $result = $query->fetch_assoc();
}
catch(Exception $e)
{
    echo 'Problem with: '.$sql;
    print_r($e); die;
}

When running the script PHP just throws me this:

Fatal error: Call to a member function fetch_assoc() on a non-object in C:\www\blackboard-import\index.php on line 227

Why this error isn't catched? Because it's fatal? How can I handle that kind of situations? I use mysqli to contact with MySQL.

webrama.pl
  • 1,870
  • 1
  • 23
  • 36

1 Answers1

5

This is no regular exception but a fatal error (which causes PHP to shut down). mysqli_query() will return false on error, this is why your current script is failing, so a solution could be something like the following

try {
    $query = $this->msqli->query($sql);
    if ($query === FALSE) {
        throw new Exception($this->mysqli->error);
    }

    $result = $query->fetch_assoc();
} catch(Exception $e) {
    //...
}
kero
  • 10,647
  • 5
  • 41
  • 51