Jump to content

Mysql query inside a foreach


bschultz

Recommended Posts

I'm trying to run a query based on matches of an array (that I've put in a foreach loop).

 

Here's the code...

 

<?php
foreach($step_three as $step_three_final)   //$step_three is an array
{
//echo $step_three_final . "<br />";

$sqlx = "SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '$step_three_final' ORDER BY priority DESC";           
echo $sqlx;
$rsx = mysql_query($sqlx,$dbc);  
while($rowx = mysql_fetch_array($rsx)) {
echo "$rowx[ump_id]<br />";
}
}
?>

 

This results is this

 

SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '1' ORDER BY priority DESC1

SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '2' ORDER BY priority DESC2

SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '4' ORDER BY priority DESC4

SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '5' ORDER BY priority DESC5

SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '6' ORDER BY priority DESC6

SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '10' ORDER BY priority DESC10

SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '14' ORDER BY priority DESC14

SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '15' ORDER BY priority DESC15

SELECT ump_id, priority FROM ump_priority WHERE `ump_id` = '18' ORDER BY priority DESC18

 

This would answer my problem...why isn't this ordering by the priority properly?...of course it's because it's running 9 queries. 

 

What is the right way to run this query...so that it will have all the records in one query...so that I can order by the priority?

 

Thanks.

Link to comment
Share on other sites

Don't run queries in loops unless absolutely necessary (and usually it isn't). Build the query string in the loop, or in this case all that's needed is implode and MySQL's IN(), then execute the query once.

 

$values = implode(', ', $step_three);
$sqlx = "SELECT ump_id, priority FROM ump_priority WHERE `ump_id` IN ($values) ORDER BY priority DESC";
$rsx = mysql_query($sqlx,$dbc);  
// ETC.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.