Php 在循环prepare语句结果时尝试获取中非对象的属性
我是PHP新手,我试图执行此函数从数据库表中选择行数,但我不明白为什么会出现此错误 注意:尝试在上的/Applications/XAMPP/xamppfiles/htdocs/Twitter/security/access.php中获取非对象的属性 第322行 第322行正在循环结果Php 在循环prepare语句结果时尝试获取中非对象的属性,php,Php,我是PHP新手,我试图执行此函数从数据库表中选择行数,但我不明白为什么会出现此错误 注意:尝试在上的/Applications/XAMPP/xamppfiles/htdocs/Twitter/security/access.php中获取非对象的属性 第322行 第322行正在循环结果 while ($row = $result->fetch_assoc()) { $returnArray[] = $row; } 这是完整的代码,这里出了什么问题(
while ($row = $result->fetch_assoc()) {
$returnArray[] = $row;
}
这是完整的代码,这里出了什么问题(
您的语句无法执行/失败,因此
$result
对象不可用。您可以使用以下方法确保获得结果:
function selectPosts($id) {
// declare array to store selected information
$returnArray = array();
// sql JOIN
$sql = "SELECT posts.id,
posts.uuid,
posts.text,
posts.path,
posts.date,
users.id,
users.username,
users.fullname,
users.email,
users.ava
FROM Twitter.posts JOIN Twitter.users ON
posts.id = ? AND users.id = ? ORDER by date DESC";
// prepare to be executed
$statement = $this->conn->prepare($sql);
$statement->bind_param('ii', $id, $id);
// error ocured
if (!$statement) {
throw new Exception($statement->error);
}
// execute sql
if (!$statement->execute()) {
//execute fails
}
// result we got in execution
$result = $statement->get_result();
if ($result === false && ($statement->errno > 0 || $this->conn->errno)) {
//result not available
}
// each time append to $returnArray new row one by one when it is found
while ($row = $result->fetch_assoc()) {
$returnArray[] = $row;
}
return $returnArray;
}
还要确保使用准备好的语句。您试图从刚才检查的语句中获取错误的尝试是错误的。在这种情况下,您需要从连接中获取错误。。 而不是
if (!$statement) {
throw new Exception($statement->error);
}
你需要
if (!$statement) {
throw new Exception($this->conn->error);
}
您还应该在执行时检查此操作是否有效
if ( !$statement->execute() ) {
throw new Exception($statement->error);
}
检查$result可能为空您的代码易受SQL注入攻击,请使用准备好的语句从Twitter帖子中删除此行中的点加入Twitter用户
if ( !$statement->execute() ) {
throw new Exception($statement->error);
}