StanUdachi StanUdachi - 1 year ago 58
PHP Question

Optimizating by changing to single query instead of putting it in to a loop

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?

Answer Source

Use IN keyword for this

$query = mysqli_query($connect, "SELECT * FROM weapons WHERE id IN (1, 8, 5, 3, 2,5) ");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download