【问题标题】:How should I make this SQL Query more efficent我应该如何使这个 SQL 查询更有效
【发布时间】:2014-01-23 02:58:51
【问题描述】:

我正在搜索数据库以查找过去 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;

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

【问题讨论】:

  • 你想循环整个sn-p,但是用2而不是1作为变量名?
  • Prepare 语句一次并重复使用它with different values
  • 你可以像这样在变量名中使用变量:$i=1; ${"day$i"}=1;

标签: php loops select mysqli


【解决方案1】:

这是你想要做的:

$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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多