php - 如何使用MySQLi处理失败?

标签 php error-handling mysqli

我目前正在开发一个使用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文档:

Returns TRUE on success or FALSE on failure.



如果我尝试检查所有这些函数调用是否为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的返回值?有没有一种整洁的方式做到这一点?

最佳答案

我会使用PDOtry-catch

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

编辑:这是MySQLi版本
try {

} catch (mysqli_sql_exception $e) {

}

关于php - 如何使用MySQLi处理失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21416455/

相关文章:

php - 如何制作一个仅显示 MySQL 中最后 20 个值的 php 动态表?

angular - Angular 6 解析器中抛出的错误丢失错误自定义类型

php - mysqli_num_rows() 期望参数 1 为 mysqli_result, object

php - 无需下载,直接将联系人导出到数据库

php - 使用 if else 显示赞助商,不显示 PHP

php - 选择多个表只在一个表中工作

php - MySQL事务超时多久

php - 递归函数返回空值

asp.net-mvc - 错误处理捕获 View 渲染异常的最后机会

sql-server - 查找 3930 SQL Server 错误的原因