我有这个查询的一部分(有效):
group_concat(`tag`.`name`) as `tags`
我将其更改为添加空格作为分隔符而不是逗号:
group_concat(`tag`.`name` ASC SEPARATOR ' ') as `tags`
现在由于这个错误它不再工作了:
Trying to get property 'num_rows' of non-object in.
这是我的 php 循环来获取结果:
$result = $conn->query($sql_query);
while($row = $result ->fetch_assoc()) {
.. the rest
有谁知道为什么 $result 突然不再是对象了?
最佳答案
您在 GROUP CONCAT
上添加了 ASC
和 SEPARATOR
. SEPARATOR
部分没问题,但 ASC
不能在没有 ORDER BY
的情况下使用。所以您的查询无效。您可以改用以下查询:
GROUP_CONCAT(`tag`.`name` ORDER BY `tag`.`name` ASC SEPARATOR ' ') AS `tags`
您正在使用 mysqli::query
执行查询并获得结果。如果您的查询无效且无法执行,您将得到 false
而不是 mysqli_result
目的。因此,您可以像下面这样改进您的代码,以确保您只访问可用的对象:
$result = $conn->query($sql_query);
//check the return value.
if ($result === false) {
echo 'something went wrong';
} elseif ($result === true) {
echo 'query executed successfully (not a SELECT statement)';
} else {
while($row = $result ->fetch_assoc()) {
//...
}
}
注意:如果您使用的是 SELECT
语句,则不需要 $result === true
条件。
关于php - 为什么当我向查询中添加某些内容时对象会在非对象中发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50697073/