You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中使用Try-Catch捕获并记录MySQLI错误失败问题排查

解决mysqli错误无法捕获写入日志且页面输出失效的问题

问题根源

  • mysqli默认采用错误返回模式:执行失败时只会返回false,并通过$conn->error或mysqli_error()返回错误信息,不会主动抛出异常,所以你的try-catch无法捕获到错误。
  • 直接设置MYSQLI_REPORT_ALL会开启所有错误报告(包括警告、注意级别的信息),这类信息会直接输出到页面,同时可能中断后续的echo输出逻辑。

解决方案

1. 开启mysqli的严格异常模式

在建立数据库连接之前,添加以下代码,让mysqli在执行出错时抛出mysqli_sql_exception异常,同时避免不必要的警告干扰页面输出:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

2. 修改try-catch逻辑

保持你的try-catch结构,捕获mysqli_sql_exception(或通用Exception,因为前者继承自后者)即可。修改后的完整代码如下:

// 先开启mysqli严格异常模式
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try
{
    $sql = "SELECT tac.Use_Agreement, tac.Privacy_Policy, tac.Age_Requirement, tac.Dispute_Resolution,
                   tac.Indemnification, tac.Liability_Limitation, tac.Pet_Appointment_Guidelines
            FROM terms_and_condition tac";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0)
    {
        $row = $result->fetch_assoc();
        $UseAgreement = htmlspecialchars($row['Use_Agreement']);
        $PrivacyPolicy = htmlspecialchars($row['Privacy_Policy']);
        $AgeRequirement = htmlspecialchars($row['Age_Requirement']);
        $Disputeresolution = htmlspecialchars($row['Dispute_Resolution']);
        $Indemnification = htmlspecialchars($row['Indemnification']);
        $LiabilityLimitation = htmlspecialchars($row['Liability_Limitation']);
        $PetAppointmentGuidelines = htmlspecialchars($row['Pet_Appointment_Guidelines']);
        echo $UseAgreement;
    }
    else
    {
        errorLogMessage($Filename.' was executed: '. 'No data were found.');
    }
}
catch (mysqli_sql_exception $e)
{
    errorLogMessage($Filename.' was executed: '. $e->getMessage());
    // 生产环境建议仅写入日志,开发环境可按需添加页面提示
}

3. 额外注意事项

  • 确保$conn是正确初始化的mysqli连接对象,且连接代码在mysqli_report设置之后执行。
  • 生产环境不要将数据库错误信息直接输出到页面,仅写入日志即可;开发环境可临时开启错误输出方便调试。

内容的提问来源于stack exchange,提问作者SoapEater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 09:25:09