Php 当我向查询中添加某些内容时,为什么非对象中的对象会发生变化
我有这个查询的一部分(这个工作): 我将其更改为添加空格作为分隔符,而不是逗号:Php 当我向查询中添加某些内容时,为什么非对象中的对象会发生变化,php,mysql,mysqli,Php,Mysql,Mysqli,我有这个查询的一部分(这个工作): 我将其更改为添加空格作为分隔符,而不是逗号: 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
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突然不再是对象了吗?您添加了
ASC
和上的分隔符。分隔符
部件很好,但是如果没有ORDER BY
,则无法使用ASC
。因此,您的查询无效。您可以改为使用以下查询:
GROUP_CONCAT(`tag`.`name` ORDER BY `tag`.`name` ASC SEPARATOR ' ') AS `tags`
您正在使用执行查询并获得结果。如果您的查询无效且无法执行,您将获得false
,而不是一个对象。因此,您可以通过以下方式改进代码,以确保仅在对象可用时访问该对象:
$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
条件。可能是因为$conn->query($sql\u query)
失败-a.k.a您中断了查询。非对象通常意味着您中断了查询。在提问之前,您是否尝试过在phpMyAdmin(或类似的工具)中运行该查询?
$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()) {
//...
}
}