user3502374 user3502374 - 3 months ago 11
MySQL Question

php running mysql_query in a for loop

I have different paramter of particular mysql query I am running so I need to run them in bunch.. so say

$server = 'server_';
for ($a=0 ; $a<5 ; ++$a) {
$criteria = $server . $a;
$query1 = 'select blabh blah not important ' . $criteria . 'order by date desc limit 10';
$query_result = mysql_query($query1);

}


Above only comes back results for server_4

I naively thought I could just do

$query_result .= mysql_query($query1);


But clearly that doesn't work. I hope no one says why don't you run mysql as
like '$server%'

I am looking for to see if what I am trying to do is possible. appending.. I guess string append is possible but I perahps simply don't understand what's coming back from mysql?

fetch code sample

select * from tableName where server like $criteria order by date desc limit 10


=========================================================
code sample

$data = array();
$dataMaster = array();

for ( $x = 0; $x <= 8; $x++ ) {
$server = ‘server_’ . $x;
$myquery = 'select * from serverTable where servername like ' . '"' . $server . '"' . ' order by date1 desc limit 100';


$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ( $x = 0; $x < mysql_num_rows($query); $x++ ) {
$data[] = mysql_fetch_assoc($query);
}

$data = array_reverse($data);
array_push($dataMaster, $data);
}

echo json_encode($dataMaster)

Answer

Try to avoid SQL inside PHP loop, you can do the following instead:

SELECT * FROM serverTable WHERE servername IN 
('server_0', 'server_1', 'server_2', 'server_3', 'server_4')
Comments