【问题标题】:How to handle failures using MySQLi?如何使用 MySQLi 处理故障?
【发布时间】:2014-01-28 20:45:25
【问题描述】:

我目前正在开发一个使用MySQLi 进行数据库访问的网站。目前执行数据库查询的代码如下所示:

$query = "SELECT height, color FROM llamas WHERE name = ?";
if(!$stmt = $connection->prepare($query)) {
   // Error handling here.
}
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($height, $color);
$stmt->fetch();
$stmt->close();

大多数这些调用的返回值返回FALSE 以指示存在问题。来自 PHP 文档:

成功返回TRUE,失败返回FALSE

如果我尝试检查所有这些函数调用是否为假,我会得到如下信息:

$query = "SELECT height, color FROM llamas WHERE name = ?";
if(!$stmt = $connection->prepare($query)) {
   // Error handling here.
}
if(!$stmt->bind_param("s", $name)) {
    // Error handling here.
}
if(!$stmt->execute()) {
    // Error handling here.
}
if(!$stmt->store_result()) {
    // Error handling here.
}
if(!$stmt->bind_result($height, $color)) {
    // Error handling here.
}
if(!$stmt->fetch()) {
    // Error handling here.
}
if(!$stmt->close()) {
    // Error handling here.
}

我的问题是:我实际上需要检查哪些函数调用的返回值FALSE?有没有一种整洁的方法?

【问题讨论】:

    标签: php error-handling mysqli


    【解决方案1】:

    我会使用 PDOtry - catch

    try {
        // your code here                   
    } catch(PDOException $e){
        error_log('ERROR: ' . $e->getMessage());
    }
    

    编辑:这是 MySQLi 版本

    try {
    
    } catch (mysqli_sql_exception $e) {
    
    }
    

    【讨论】:

    • 这看起来确实是一个不错的解决方案,但不幸的是,该网站已经建立在 MySQLi 上,将其转换为 PDO 需要相当多的努力。
    • @DanielGibbs 我已经添加了 MySQLi 版本
    • 上述方法真的会抛出mysql_sql_exception吗?我在文档中看不到有关他们这样做的任何内容。
    猜你喜欢
    • 1970-01-01
    • 2018-06-09
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多