need help with loop

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
knightsjoker
Forum Newbie
Posts: 13
Joined: Fri Dec 26, 2008 2:00 am

need help with loop

Post 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.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: need help with loop

Post 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?
There are 10 types of people in this world, those who understand binary and those who don't
knightsjoker
Forum Newbie
Posts: 13
Joined: Fri Dec 26, 2008 2:00 am

Re: need help with loop

Post 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
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: need help with loop

Post 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.
Post Reply