这个问题在这里已经有了答案:
Fatal error: Call to a member function fetch_assoc() on a non-object [duplicate]
(4 个回答)
4年前关闭。
我正在尝试编写“通用”函数来执行 SQL 查询并返回 JSON 并处理其中的错误。在这个过程中,我不明白为什么 try catch 块不处理错误。 (稍后我将改进逻辑 - 问题不是关于那个,而是纯粹关于错误处理)。
这是我的代码:
public
function sqlToJSON($query, $type = array(), $params = array())
{
try {
$data = array();
$stmt = $this->mysqli->prepare($query);
if (count($type) > 0 && count($params) > 0) {
call_user_func_array(array($stmt, "bind_param"), array_merge(array($type), $params));
}
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
$stmt->free_result();
$stmt->close();
return array('result' => 'success', 'error' => null, 'data' => $data);
} catch (Exception $e) {
$this->sqlError = 'Caught exception: ' . $e->getMessage();
return array('result' => 'failed', 'error' => $e->getMessage(), 'data' => null);
}
}
我如何调用这个函数:
$q = 'INSERT INTO receivers (receiver_name, owner) VALUES (UPPER(?), ?)';
$params = array(&$receiverName, &$clientEmail);
$this->sqlToJSON($q, 'ss', $params);
这给出了以下预期错误:
Uncaught Error: Call to a member function fetch_assoc() on boolean in ...
我不明白为什么在这种情况下不执行 catch 块?
最佳答案
在 php 中,错误不是异常(exception)。如果您想捕获它们,请编写您自己的 error_handler。 http://php.net/manual/en/function.set-error-handler.php
关于php - try catch block 中的未捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42362957/