Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need help in order to assign the results of a nested query into array. This is the scenario:

$Date_Collection = mysql_query("SELECT DISTINCT Date FROM TblDate");

while($date = mysql_fetch_array($Date_Collection)) // Loop through all the dates
{
    $var_date = $date['Date'];
    $result = mysql_query("select min(Speed) as Min_spd, max (Speed) as Max_spd, avg   
                  (Speed) as Avg_spd from ... where Date= $var_date");

  while($row = mysql_fetch_array($result))
   {
     echo "row[Min_spd]";
     echo "row[Max_spd]";
     echo "row[Avg_spd]";
    }
 }

The output from this query is like this:

Min_Spd |Max_Spd |Avg_Spd|       Date|
    12.0|    25.0|   20.4| 2012-10-01|
    11.0|    28.0|   21.4| 2012-10-02|
    10.0|    26.0|   23.4| 2012-10-05|
    08.0|    22.0|   21.4| 2012-10-08|

I basically need to show the sum of Min_Spd, Sum of Max_spd, Sum of Avg_spd for all these dates. So, I thought that If I can assign these values into an array and later compute these sum from the array, it might be a good idea.

Can anyone please help me regarding this? Can I use an array to store the values and later access these values and calculate the sum of these values. If I can use an array, could anyone please show me the syntax of using array in PHP. I would really appreciate any help regarding this.

Is there any alternative way rather than using an array, such as creating a temporary table to save these values and later delete the temporary table. If a temporary table can be used, could you please show me how to do that. I could use the temptable for a single loop, but there is a nested loop and I don't exactly know what to do to create a temp table inside the nested loop to store all the values.

share|improve this question

4 Answers

Instead of doing several MySQL queries in a loop, consider constructing such a query, which will return all the results you need.

SQL

First of all, it would make sense to use the GROUP SQL construct.

SELECT
    s.Date       date,
    MIN(s.Speed) min,
    MAX(s.Speed) max,
    AVG(s.Speed) avg
FROM speed_table s
WHERE s.Date IN (SELECT DISTINCT d.Date FROM date_table d)
GROUP BY s.Date

It is important to understand what each part of this query does. If you run into any problems, consult the MySQL reference manual.

PHP

Forget about using mysql_* functions: they are deprecated and better implementations have emerged: PDO and mysqli. My example uses PDO.

try {
    $dbh = new \PDO('mysql:dbname=my_db_name;host=127.0.0.1', 'dbuser', 'dbpass');
} catch (\PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$sql  = '...';  // This is the query
$stmt = $pdo->prepare($sql);
$stmt->execute();

You can now either iterate over the returned result set

while ($row = $stmt->fetch()) {
    printf("%s; %s; %s; %s\n", $row['date'], $row['min'], $row['max'], $row['avg']);
}

or have the Statement object return the whole array by using

$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
share|improve this answer
Thanks for the suggestion. I will try as you suggested. – Tariq Jul 9 '12 at 22:09

I would first of all save yourself a nested query by doing the first query as:

$result = mysql_query("select Date, min(Speed) as Min_spd, max (Speed) as Max_spd, avg(Speed) as Avg_spd from ... group by Date")

And then create a running total for the sums as you're looping through each row:

$sumMinSpeeds=0;
$sumMaxSpeeds=0;
$sumAvgSpeeds=0;
while($row = mysql_fetch_array($result))
{
    echo row['Min_spd'];
    echo row['Max_spd'];
    echo row['Avg_spd'];

    $sumMinSpeeds += $row['Min_spd'];
    $sumMinSpeeds += $row['Max_spd'];
    $sumMinSpeeds += $row['Avg_spd'];

}
echo $sumMinSpeeds;
echo $sumMaxSpeeds;
echo $sumAvgSpeeds;
share|improve this answer
Thanks for the suggestion. I will try as you suggested. – Tariq Jul 9 '12 at 22:08

I don't know if the MySQL SUM function can be used to do that on te query, try it. But on this example, using arrays you should store the values and then use array_sum to return the sum of the elements. Something like this:

$min_spd = array();
$max_spd = array();
$avg_spd = array();
while($row = mysql_fetch_assoc($result))
{
    $min_spd[] = $row['Min_spd'];
    $max_spd[] = $row['Max_spd'];
    $avg_spd[] = $row['Avg_spd'];
}

echo array_sum($min_spd);

It can also be done using variables to store and add the values:

$min_spd = 0;
$max_spd = 0;
$avg_spd = 0;

while($row = mysql_fetch_assoc($result))
{
    $min_spd += $row['Min_spd'];
    $max_spd += $row['Max_spd'];
    $avg_spd += $row['Avg_spd'];
}

echo $min_spd;
share|improve this answer
Thanks for the suggestion. I will try as you suggested. – Tariq Jul 9 '12 at 22:07
$data = array();
while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row;
}

then later on you can do

foreach($data as $row) {
   echo $row['Min_spd'];
   echo ...
   ...
}
share|improve this answer
Thanks for the suggestion. I will try as you suggested. – Tariq Jul 9 '12 at 22:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.