如何从数据库中选择存储在Array中的相同ID?

时间:2016-04-03 16:45:12

标签: php sql

我已将ID存储为评分帖子的用户的STRING。例如:

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

我稍后将字符串转换为数组:

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

现在我想查询另一个表并选择在数组$kaboom中找到id的所有字段。我试过但是我收到以下错误:

  

注意:第22行的C:\ xampp \ htdocs \ cebs \ include \ post_reacts.php中的数组到字符串转换

这是我的代码:

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

    }               
}
}
?>

1 个答案:

答案 0 :(得分:3)

您可以使用IN(...)

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

使用IN的查询如下所示:

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

因此,您事先无需explode进入数组。