有没有办法将事件处理函数附加到mysql错误?

时间:2013-07-03 00:02:24

标签: php mysql mysqli

目前,处理mysql错误的最佳方法是在每个mysql语句之后添加:

if($mysqli->error)
errorhandlingfunction();

有没有办法为mysql错误创建一种处理程序,并在每次出现错误时分配一个函数,而不是每次都要手动检查?

1 个答案:

答案 0 :(得分:0)

创建一个扩展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块的内容显然可能更大,包含多个查询。