如何在PHP和MySQL中生成统计日期范围报告?

时间:2014-11-13 16:37:03

标签: php mysql

我正在尝试制作日期范围报告,这是我迄今为止的目标。

表格

<form class="daterangeform" method="POST" action="datereport.php">
                <fieldset id="daterangefield">
                    <legend><b>Date Range Report</b></legend>
                    <div class= "group1">
                        <div class = "group2">
                            <label for="fromdate"> From </label>
                            <br/>
                            <input type="date" name="fromdate" required/>
                        </div>
                        <div class = "group2">
                            <label for="todate"> To </label>
                            <br/>
                            <input type="date" name="todate" required/>
                        </div>
                        <br/>
                    </div>
                </fieldset>
                <br/>
                    <div class="formbuttons">
                        <input name= "formsubmit" id="formsubmit" type="submit" value="Generate Report" />
                    </div>
</form>

MySQL查询(显示&#39;成功&#39;)

if(isset($_POST['formsubmit']))
{
    $fromdate=mysql_real_escape_string($_POST['fromdate']);
    $todate=mysql_real_escape_string($_POST['todate']);

    $sql = "select crime_type, count(*) from cases where commitment_date between '$fromdate' and '$todate' group by crime_type;";

    if($db->query($sql))
    {
        echo "success";
    }
    else
    {
        echo(mysql_error());
    }
}

这就是我想要实现的目标。例如,有犯罪类型&#39;抢劫&#39;突击&#39;和交通事故&#39;当我选择日期范围并提交表格时,我希望它计算该特定范围内的抢劫,袭击和交通事故的数量,并将其显示在表格中。我不确定上面的查询是否适用于此。另外,请帮助我如何显示值,因为我是初学者。提前谢谢。

1 个答案:

答案 0 :(得分:0)

这里有一点可能会有所帮助。您还应该切换到使用mysqli函数,但这是另一个主题。我没有对此进行测试,因此可能会出错,但这是一般的想法。

if(isset($_POST['formsubmit']))
{
  $fromdate=mysql_real_escape_string($_POST['fromdate']);
  $todate=mysql_real_escape_string($_POST['todate']);

  ##Added the count alias##
  $sql = "SELECT crime_type, count(*) as count 
          FROM cases 
          WHERE commitment_date 
          BETWEEN '$fromdate' and '$todate' 
          GROUP BY crime_type;";

 ##assigned the query to a variable##
 $result = $db->query($sql);

 ##if at least 1 result##
  if($result && (mysql_num_rows($result) > 0))
  {
     ##echo everything into a table##
      echo "<table><thead><tr><th>Crime type</th><th>Count</th></tr></thead>";
      while ($row = mysql_fetch_assoc($result))
      {
          echo "<tr><td>".$row['crime_type']."</td><td>".$row['count']."</td></tr>";
       }
      echo "</table>";
  }
  else
  {
      ##There won't be an error thrown for an empty result set##
      echo "<h2>No records found...</h2>";
  }
}