1

I have a table in data base. It contains 3 columns: ID, name, type. I have an array in my PHP script with some of those IDs (not in any order, maybe duplicates). I want to echo out those items from the table, that I have IDs in the array. I tried doing this with a for loop:

$items = array(1, 8, 5, 3, 2, 1,  5, 5);
for ($i=0; $i < count($items); $i++) {
    $query = mysqli_query($connect, "SELECT * FROM weapons WHERE id='$items[$i]'");
    $row = $query->fetch_assoc();

    echo $row['name'] . ', ' . $row['type'];
}

I think its not good practice to use call query in a loop, because if the loop gets too big, it may slow that the process. What can I achieve the same result, without putting query in a loop?

StanUdachi
  • 13
  • 2
  • You can use `IN` instead of `=`. Check this http://stackoverflow.com/questions/16240041/sql-search-multiple-values-in-same-field – Aman Rawat Sep 24 '16 at 05:46
  • @AmanRawat This method doesn't work with duplicates. If I have the same thing more than once in the IN selector, it would just get once. What should I change? – StanUdachi Sep 24 '16 at 19:24

2 Answers2

3

Use IN keyword for this

$query = mysqli_query($connect, "SELECT * FROM weapons WHERE id IN (1, 8, 5, 3, 2,5) ");
Gulmuhammad Akbari
  • 1,986
  • 2
  • 13
  • 28
0
$query = mysqli_query($connect, "SELECT * FROM weapons WHERE id IN (1, 8, 5, 3, 2,5) ");
while($row = $query->fetch_assoc())
{
echo $row['name'] . ', ' . $row['type'];
}