Page 1 of 1

need help with loop

Posted: Fri Nov 13, 2009 9:25 am
by knightsjoker
Need help with the below loop. I'm trying to optimize below with while / for loop:

Code: Select all

 
$t11="SELECT count(r1) from table WHERE r1 = '1'";
$t12="SELECT count(r1) from table WHERE r1 = '2'";
$t13="SELECT count(r1) from table f WHERE r1 = '3'";
$t14="SELECT count(r1) from table WHERE r1 = '4'";
$$t15="SELECT count(r1) from table WHERE r1 = '5'";
$t16="SELECT count(r1) from table WHERE r1 = '6'";
 
so i tried putting it inside

Code: Select all

 
$i = 0;
while ($i <= 6)
{
$gt1[$i]="SELECT count(r1) FROM table WHERE r1 = '$i'";
}
 
but it's returning the array. I need to return the value one by one:

$gt11 = '0';
$gt12 = '0';
$gt13 = '1';
$gt14 = '0';
$gt15 = '1';
$gt16 = '0';

any help would be appreciated.

Re: need help with loop

Posted: Fri Nov 13, 2009 10:15 am
by VladSun
Take a look at the results from this query:
[sql]SELECT r1, count(r1) AS count_r1 FROM TABLE GROUP BY r1[/sql]

Is it optimized?

Re: need help with loop

Posted: Fri Nov 13, 2009 6:41 pm
by knightsjoker
nope. that one i've tried.

it has something to do with $t1

i want it to loop to get count for $gt11, $gt12, $gt13 etc

Re: need help with loop

Posted: Wed Nov 18, 2009 7:03 am
by Weiry
knightsjoker wrote:but it's returning the array. I need to return the value one by one:
If you need to run through each query which is stored in the array, why not use a foreach loop?

Code: Select all

<?php
for($i = 0; $i <= 6; $i++){
    $gt1[$i]="SELECT count(r1) FROM table WHERE r1 = '$i'";
}
foreach($gt1 as $query){
   print $query."<br/>";
}
?>
Doing this will return only a single query each time it is printed inside the foreach loop, which is where you would probably do your query execution.