0

I want to make a dynamic WHERE clause to find posts by multiple posters. This is my code so far.

$in = join(',', array_fill(0, count($myArray), "?"));
$query = "SELECT * FROM posts WHERE poster IN ($in)";
$statement = $conn->prepare($query);
$statement->bind_param(str_repeat("s", count($myArray)), ...$myArray);
$statement->execute();
$result = $statement->get_result();

The above code is working but only for the very first person in my array. How will I be able to get the posts from every person listed in the array?

zam
  • 58
  • 2
  • 9
  • Can't answer this until you give us an idea of what is in `$myArray`.... – random_user_name Mar 28 '16 at 23:32
  • As a matter of practice, you should not use aliases. [join](http://php.net/manual/en/function.join.php) is an alias of [implode](http://php.net/manual/en/function.implode.php). It may work now, but wait until they decide to deprecate aliases for some reason (it happens). – random_user_name Mar 28 '16 at 23:33
  • For example, $myArray is Array ( [0] => krithik [1] => alex ) $myArray just contains strings of a user's username. – zam Mar 28 '16 at 23:33
  • Possible duplicate of [How to bind mysqli bind\_param arguments dynamically in PHP?](http://stackoverflow.com/questions/5100046/how-to-bind-mysqli-bind-param-arguments-dynamically-in-php) – random_user_name Mar 28 '16 at 23:37
  • This code works. the problem is with your array and/or database. – Your Common Sense Mar 29 '16 at 05:04
  • What do you mean? How would I fix my array and/or database? – zam Mar 29 '16 at 05:05

1 Answers1

-4

Build up a string and append it to $query using a foreach loop

$where = "where poster IN ( "
foreach ($myArray as $value) {
    $where = $where + "'" + $value + "'"
}
 $where = $where + " )"
user2202098
  • 830
  • 1
  • 9
  • 24
  • Negative. You don't use `+` for concatenation in PHP (that's javascript). Plus you need semi-colons. Plus you should CAP CASE keywords such as `AS` – random_user_name Mar 28 '16 at 23:30
  • 1
    This defeats the entire purpose of using prepared statements. Please don't recommend this. – tadman Mar 28 '16 at 23:32