2014-01-28 42 views
0

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

返回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?有没有一个完整的方式来做到这一点?

回答

0

我会用PDOtry - catch

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

编辑:这里是库MySQLi版本

try { 

} catch (mysqli_sql_exception $e) { 

} 
+0

这看起来像一个很好的解决方案,但遗憾的是该网站已经建立在库MySQLi将其转换为PDO需要相当多的努力。 – DanielGibbs

+0

@DanielGibbs我已经添加了MySQLi版本 – cmorrissey

+0

上面的方法是否真的会抛出一个'mysql_sql_exception'?我看不到有关他们这样做的文档中的任何内容。 – DanielGibbs