0

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...
        }

    }               
}
}
?>
2
  • 3
    @Mihai: I think that should be WHERE ids IN ($ids) - $kaboom is the exploded version, which would be cast back to the string Array anyway. Commented Apr 3, 2016 at 16:50
  • 1
    OP, just be careful that $ids is not tainted - if it comes from the user then you will have to explode it, clean it, and implode it again. Commented Apr 3, 2016 at 16:51

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So this means if i was gonna use the explode then i will have to implode and push it back into a string which is not necessary in this case.
If you already have a comma separated string of ID's, then nothing else is required. You can just put it in the query as it is.
@bytecode77: bear in mind that if the CSV string comes from user input, then putting it in the query as it is is a security risk. It's not clear if it is tainted in this case.
I know that. But it's not related to the OP's question and problem. It's a different problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.