-3

Is it possible to run this code 24 times in order to find per hour value without copy and pasting the code 24 times.

<?php
  $result = mysql_query('SELECT date,SUM(value) AS value_sum FROM me Where WEEKDAY(date) >="6" AND HOUR(date)="0" '); 
  $row = mysql_fetch_assoc($result); 
  $h0= $row['value_sum'];
?>

<?php
  $result = mysql_query('SELECT date,SUM(value) AS value_sum FROM me Where WEEKDAY(date) >="6" AND HOUR(date)="1" '); 
  $row = mysql_fetch_assoc($result); 
  $h1= $row['value_sum'];
?>
beoliver
  • 5,068
  • 5
  • 29
  • 68
Ian
  • 3
  • 2

2 Answers2

0

I'd suggest you modify your SQL statement in order to get all tuples in one access, and then loop over the tuples (in memory) to sum up the value items:

// Query the database
$result = mysql_query('SELECT date, value FROM me Where WEEKDAY(date) >="6" AND HOUR(date) >= "0" AND HOUR(date) < "24"');

// Sum values up
$h1 = 0;
while($row = mysql_fetch_assoc($result)) {
    $h1 += $row['value'];
} 

Executing an SQL statement - for several reasons - uses considerably more resources, and takes longer, than executing PHP code in a loop over all elements of an array.

This solution would execute one SQL query only instead of 24 queries.

(And, yes: use mysqli or PDO instead of mysql, which is deprecated)

hherger
  • 1,636
  • 1
  • 8
  • 13
-1

Try using a for loop and add your results into an array.

<?php
  $resultArray = array();
  for($i = 0; $i < 24; $i++;) {
     $result = mysql_query('SELECT date,SUM(value) AS value_sum FROM me Where WEEKDAY(date) >="6" AND HOUR(date)="' . $i . '" '); 
     $row = mysql_fetch_assoc($result); 
     resultArray[] = $row['value_sum'];
  }
?>
Natalie Hedström
  • 2,476
  • 2
  • 21
  • 33