James Favour
James Favour

Reputation: 79

How to SELECT same IDs from database which are stored in Array?

I have stored IDs as STRING of users who rated a post. Example:

$ids="5,8,4,9,7,8,87";

and I later convert the string into an array:

$kaboom = explode(',',$ids);

Now I want to query another table and select all field where the id is found in array $kaboom. I tried but I get the following error:

Notice: Array to string conversion in C:\xampp\htdocs\cebs\include\post_reacts.php on line 22

This is my code:

<?php
//include connection file
include 'dbc.php';


if(isset($_POST['post_id'])){
$post_id = $_POST['post_id'];

//SELECT ALL IDS OF THOSE WHO RATED THE POST

$query = mysqli_query($dbc_conn,"SELECT highlight_voters FROM $public_feed_table WHERE id='$post_id' LIMIT 1");

if($query==true){

while($row=mysqli_fetch_assoc($query)){
$ids = $row['highlight_voters'];
$kaboom = explode(",",$ids);


//select IDS which is/are in array and and get details about the ID

$check_ids_which_in_array = mysqli_query($dbc_conn,"SELECT * FROM $table_name WHERE id='$kaboom' ");

}

if($check_ids_which_in_array==true){
while($b=mysqli_fetch_assoc($check_ids_which_in_array)){
$person_who_rated =$b['id'];

    //do something here after...
        }

    }               
}
}
?>

Upvotes: 0

Views: 69

Answers (1)

bytecode77
bytecode77

Reputation: 14840

You can use IN(...)

mysqli_query($dbc_conn, "SELECT * FROM $table_name WHERE id IN($ids)")

A query that uses IN would look like this:

SELECT * FROM table WHERE id IN(1, 2, 3, 7, 8, 9)

Therefore, you don't need to explode into an array beforehand.

Upvotes: 3

Related Questions