每当查询执行完毕,我知道您应该释放结果。下面是我为运行一个简单查询而构建的一个类的片段。有人能告诉我哪里出了问题吗?如果输入正确,查询将成功运行。只是我的页面没有像它那样重新加载,应该这样,但它给了我这些错误。。。
Fatal error: Call to a member function free() on a non-object in <file> on <line>
而这个错误。。。
Fatal error: Call to a member function close() on a non-object in <file> on <line>
这里是我代码的简化版本:
public function query($query) {
try {
if ($result = $this->connection->query($query, MYSQLI_USE_RESULT)) {
$result->free(); //Problems here
$result->close(); //Problems here
return $result;
} else {
$result->free(); //Problems here
$result->close(); //Problems here
throw new Exception("The query was invalid");
}
} catch (Exception $e) {
die($e->getMessage());
}
}
如果我按照您的手册链接,会提到一些关于返回值的内容
失败时返回FALSE。对于成功的SELECT、SHOW、DESCRIBE或EXPLAIN查询,mysqli_query()将返回一个结果对象。对于其他成功的查询,mysqli_query()将返回TRUE。
特别是你没有处理true
和更重要的false
这两种情况
if ($result = $this->connection->query($query, MYSQLI_USE_RESULT)) {
$result->free(); // Probably call "free()" on true
$result->close();
return $result;
} else { // <-- false, null, 0 or ""
$result->free(); // Probably call "free()" on false
$result->close();
throw new Exception("The query was invalid");
}
我不知道$query
在您的情况下是什么,但query()
只会返回一个结果,如果有一个结果(SELECT
-查询)。