-1

I have the following code:

$db = new mysqli('localhost', 'xxx', 'xxx', 'dbname');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

    try 
    {
       $db->begin_transaction();
       $db->query($q_insert_custom);
       $db->commit();
       $error_message = '';
    }
    catch (Exception $e) 
    {
       $db->rollback();
       $error_message = $e->getMessage()." **** LINE: ".$e->getLine();
    }

    echo $error_message;

There is a problem in $q_insert_custom in that it's trying to insert a row but a required field is missing. When you run the query in MySQL Workbench, I get an error about the query and how it's missing the field. But when I run it via PHP is doesn't get caught with exception handling and it appears as if the query ran just fine.

What am I doing wrong? How do I catch when MySQL throws an error about a query?

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194

1 Answers1

-1

A quick way to find MySQL error is to check if there is a message in $db->error. Then you can throw it throw new Exception($db->error);, if needed.

Todor
  • 43
  • 1
  • 8