致命错误:在布尔值上调用成员函数fetch_assoc()

时间:2015-03-10 20:04:20

标签: php mysql

我想只选择authorId只有1和2的帖子。我这样做:

$array = [1,2];
$array = implode(", ",$array);
$sql = "SELECT * FROM post WHERE authorId = ({$array})";
$res = $con->query($sql);

while($row = $res->fetch_assoc()){
    echo $row['firstname'] . ' ' . $row['lastname'];
}

我收到错误消息:

Fatal error: Call to a member function fetch_assoc() on boolean in C:\xampp\blablaba.php on line blablaba

但是当我试图从一位作者那里获得帖子时,我没有收到任何错误消息。实际上它有效,这是我的一个authorId的代码:

$sql = "SELECT * FROM post WHERE authorId = 1)";
$res = $con->query($sql);

while($row = $res->fetch_assoc()){
    echo $row['firstname'] . ' ' . $row['lastname'];
}

2 个答案:

答案 0 :(得分:2)

对于此代码:

$array = [1,2];
$array = implode(", ",$array);
$sql = "SELECT * FROM post WHERE authorId = ({$array})";

原始sql查询将是:

"SELECT * FROM post WHERE authorId = ('1, 2')"

首先,您可以使用' IN'更改查询。操作者:

"SELECT * FROM post WHERE authorId IN ({$array})"

原始查询:

"SELECT * FROM post WHERE authorId IN ('1, 2')"

但是,IN ('1, 2')的类型是一个字符串,这可能是整数值列表。您必须使用CAST函数将此字符串转换为char值集:

CAST($array as CHAR);

现在,在此集合中找到FIND_IN_SET函数:

 FIND_IN_SET(authorId, CAST($array as CHAR));

最终的SQL查询将是:

"SELECT * FROM post WHERE FIND_IN_SET(authorId, CAST($array as CHAR));"

原始查询:

"SELECT * FROM post WHERE authorId IN (1, 2);"

答案 1 :(得分:1)

$array = [1,2];
$sql = "SELECT * FROM post WHERE authorId IN (".implode(",",$array).")";