0

According to this PHP documentation on mysqli::prepare(), it appears that the return value should be a statement object or false.

In the example below, I made a mistake in changing an INSERT INTO to a REPLACE INTO, and the error-handler code never executed but the catch picked up a 1064 error.

Is this the expected behavior? Why didn't $db->prepare($sql) return false? Does using try/catch pick up the error before the return?

Thank you.

try {
  $sql = " INSERT REPLACE INTO ... WHERE id=?";
  if ( !($stmt = $db->prepare($sql) ) ) {
    /* error handler code */
  }
} catch ( Exception $err ) {
  $res['r'] = $err->getCode();
  $res['m'] = $err->getMessage();
}
 
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Gary
  • 2,393
  • 12
  • 31
  • 2
    This entirely depends on how you've configured [mysqli_report()](https://www.php.net/manual/function.mysqli-report.php). In your case, it looks like you've got it throwing exceptions which will happen instead of any value being returned from `prepare()`, `execute()`, etc – Phil May 30 '22 at 05:11
  • @Phil What is supposed to be done with duplicate questions? Am I to delete it? – Gary May 30 '22 at 05:24
  • There's some info [here](https://stackoverflow.com/help/duplicates) but in general, I don't think you need to do anything. Leaving your question here can help boost SEO for the _canonical_ answer. – Phil May 30 '22 at 05:27
  • 2
    Yes, this is how exceptions work, exactly. But obviously, it not a "try catch" that prevents the returning of value, but *throw*, called internally by prepare(). While having try-catch doesn't change anything here. But in the first place, why do you have *two handlers*? What's the use of this $res['r'] and $res['m']? – Your Common Sense May 30 '22 at 05:55
  • Why do you catch errors at all? If you have an error in your SQL that should result in a fatal error, unless you have a way to recover from it. – Dharman May 30 '22 at 14:12

0 Answers0