Создайте новый класс, который расширяет mysqli
и генерирует исключение при возникновении ошибки:
/* Create custom exception classes */
class ConnectException extends Exception {}
class QueryException extends Exception {}
class Mysqlie extends mysqli
{
function __construct()
{
parent::init();
if (!parent::options(MYSQLI_INIT_COMMAND, 'set session sql_mode="strict_all_tables";')) {
throw new ConnectException("Cannot set MySQL options");
}
$args = func_get_args();
$result = call_user_func_array("parent::real_connect", $args);
/* Pass all arguments passed to the constructor on to the parent's constructor */
if (!$result) {
throw new ConnectException('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
}
function query($query)
{
$result = parent::query($query);
if(mysqli_error($this)){
throw new QueryException(mysqli_error($this), mysqli_errno($this));
}
return $result;
}
}
Тогда ваш код становится:
try {
$conn = new mysqlie(...connection parameters...);
$result = $conn->query("MyQuery");
// do lots more stuff here
// including more queries
$result = $conn->query("MyNextQuery");
// finally close...
$conn->close();
} catch (ConnectException $e)) {
die("Can't connect to database".$e->getMessage());
} catch (QueryException $e) {
die("Query error:".$e->getMessage());
}
Содержание вашего try
блока может быть, очевидно, гораздо больше, и включать несколько запросов.
Возможный дубликат [MySQLi обработки ошибок] (http://stackoverflow.com/questions/2932113/mysqli-error-handling) – peterm