我正在尝试从 5 个表中选择所有来自相同会话 ID 的列。 但是我收到了这个:试图获取非对象的属性“num_rows”。 这是我的代码:
<?php
include 'db.php';
$sql = "SELECT users.username,
bank.cash_on_hand, bank.bank,
ranking.rank, ranking.level_points,
_location.location,
bullets.bullets, bullets.backfire
FROM users, bank, bank, ranking, ranking, _location, bullets, bullets
WHERE id = '".$_SESSION["id"]."' ";
$result = $conn->prepare($sql);
if($result-> num_rows > 0)
{
while ($row = $result-> fetch_assoc())
{
echo "<table>".
"<tr>
<th>username |</th>
<th>cash on hand |</th>
<th>bank |</th>
<th>rank |</th>
<th>level_points |</th>
<th>location |</th>
<th>bullets |</th>
<th>backfire </th>
</tr>".
"<tr>".
"<td>". $row["username"]. "</td>".
"<td>". $row["cash_on_hand"]. "</td>".
"<td>". $row["bank"]. "</td>".
"<td>". $row["rank"]. "</td>".
"<td>". $row["level_points"]. "</td>".
"<td>". $row["_location"]. "</td>".
"<td>". $row["bullets"]. "</td>".
"<td>". $row["backfire"]. "</td>".
"</tr>".
"</tr>".
"</table>";
}
}
else
{
echo "0 result";
}
?>
我收到此错误:Trying to get property 'num_rows' of non-object in C:\wamp64\www\phil\player_info_bar.php on line 27
&第 27 行是这样的:if($result-> num_rows > 0)
我该如何解决这个问题?
答案 0 :(得分:1)
您已准备好 sql,但尚未执行。
试试:
$result->execute(); $res = $stmt->get_result(); $row = $res->fetch_assoc();
答案 1 :(得分:-1)
您可能有两个选项来执行查询
首先:将 $result = $conn->prepare($sql) 替换为下面
$stmt = $conn->prepare($sql);
$result = $stmt->execute();
或者 第二:将 $result = $conn->prepare($sql) 替换为下面
$result = $conn->query($sql);
注意:您的查询还应为每个表包含一次表名。
答案 2 :(得分:-3)
乍一看,您的查询是错误的(至少对于不明确的列名 id),因此失败且不返回行。
假设您的所有表都通过列名 id 与会话相关。
"SELECT users.username,
bank.cash_on_hand, bank.bank,
ranking.rank, ranking.level_points,
_location.location,
bullets.bullets, bullets.backfire
FROM users
INNER JOIN bank ON bank.id = users.id
INNER JOIN ranking ON ranking.id = users.id
INNER JOIN _location ON _location.id = users.id
INNER JOIN bullets ON bullets.id = users.id
WHERE users.id = '".$_SESSION["id"]."' ";
无论如何,您不应该在 FROM 子句中错误地使用同一个表,因为这只会产生笛卡尔积并返回与两个表中相关事件相乘的相同行
您不应该使用基于逗号分隔表名称的旧连接语法,您应该使用基于连接声明和 ON 子句的显式连接子句。
最后(但并非最不重要)你不应该在 where 子句中使用 php var .. 你有 SQL 注入的风险。为避免这种情况,您应该查看 MySQL 驱动程序的准备语句和绑定参数。
准备不执行查询。试试这个:
$result = $conn->query($sql);