1

I want to select only posts where authorId is only 1 and 2. And i do that like this:

$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'];
}

I got error message:

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

But when i try to get posts just from one author i dont get any error message. Actually it works, here is my code for one authorId:

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

while($row = $res->fetch_assoc()){
    echo $row['firstname'] . ' ' . $row['lastname'];
}
Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
Buzzzz
  • 81
  • 1
  • 3
  • 9

2 Answers2

2

For this code:

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

raw sql query will be:

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

First, you can change you query with using 'IN' operator:

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

raw query:

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

but, type of IN ('1, 2') is a string, when this may be list of integer values. You must convert this string to the set of char values with CAST function:

CAST($array as CHAR);

and, now, find in this set with FIND_IN_SET function:

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

Final sql query will be:

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

Raw query:

"SELECT * FROM post WHERE authorId IN (1, 2);"
1
$array = [1,2];
$sql = "SELECT * FROM post WHERE authorId IN (".implode(",",$array).")";
steven
  • 4,868
  • 2
  • 28
  • 58