我应该如何使这个SQL查询更有效

时间:2014-01-23 02:58:51

标签: php loops select mysqli

我正在搜索数据库以查找过去7天的累积数据。

它运行完美,但我目前有七个版本的相同代码 - 所以我想以某种方式循环它,但是如果我这样做,我如何正确循环并命名变量。除了命名变量(day_X_)之外,我想我应该能够很容易地将它循环7次......

// Get the current day
$graph_day_1_date_lower = date('Y-m-d') . " 00:00";
$graph_day_1_date_upper = date('Y-m-d') . " 23:59";
$graph_day_1_name = date('D') . " (Today)";
/* Successes */
$graph_day_1 = mysqli_query($con, 
   "SELECT COUNT(`id`) AS num FROM `hidden` 
   WHERE submittedtime >= '$graph_day_1_date_lower' 
   AND submittedtime < '$graph_day_1_date_upper' 
   AND u_s_code='C001'") 
 or die(mysqli_error($con));
$graph_day_1_row = mysqli_fetch_assoc($graph_day_1);
$graph_day_1_count = $graph_day_1_row['num'];
$graph_total_count = $graph_day_1_count;
/* Errors */
$graph_e_day_1 = mysqli_query($con, 
  "SELECT COUNT(`id`) AS num FROM `hidden` 
  WHERE submittedtime >= '$graph_day_1_date_lower' 
  AND submittedtime < '$graph_day_1_date_upper' 
  AND u_s_code='E001'") 
or die(mysqli_error($con));

$graph_e_day_1_row = mysqli_fetch_assoc($graph_e_day_1);
$graph_e_day_1_count = $graph_e_day_1_row['num'];
$graph_e_total_count = $graph_e_day_1_count;

然后我将打印每天的两个总计数

1 个答案:

答案 0 :(得分:0)

以下是您想要做的事情:

$today = time(); // or use your upper / lower bounds
$daysToShow = 7;
$dayData = array();

for($i = 0; $i < $daysToShow; $i++){
   $dateToCheck = $today + ($i * 24 * 60 * 60); // add a day each time $i goes up
   $dataArray = mysql_fetch_assoc($yourDataHere); // replace with your mysqli query using $dateToCheck
   $dayData[] = $dataArray; // add to array
}

foreach($dayData as $day){
   echo $day['name']; // print out your info here
}