我目前正在开发一个使用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 orFALSE
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
的返回值?有没有一种整洁的方式做到这一点?
最佳答案
我会使用PDO
和try
-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/