0

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

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

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

4

1 回答 1

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显然可能要大得多,并且包括多个查询。

于 2013-07-03T00:24:43.933 回答