我正在尝试根据日期在表格中显示数据,目前正在使用以下代码。
if($_GET){
$datefrom = $_GET['datefrom'];
$dateto = $_GET['dateto'];
$date0 = date('Y-m-d', strtotime($datefrom . " +0 days"));
$date1 = date('Y-m-d', strtotime($datefrom . " +1 days"));
$date2 = date('Y-m-d', strtotime($datefrom . " +2 days"));
$date3 = date('Y-m-d', strtotime($datefrom . " +3 days"));
$date4 = date('Y-m-d', strtotime($datefrom . " +4 days"));
}
然后我使用以下语句重复查询我的数据库
$stmtHR0 = $db->query("SELECT * FROM table WHERE Form_Date = '$date0' AND State = 'HR'");
$numHR0 = $stmtHR0->rowCount();
$stmtHR1 = $db->query("SELECT * FROM table WHERE Form_Date = '$date1' AND State = 'HR'");
$numHR1 = $stmtHR1->rowCount();
$stmtHR2 = $db->query("SELECT * FROM table WHERE Form_Date = '$date2' AND State = 'HR'");
$numHR2 = $stmtHR2->rowCount();
$stmtHR3 = $db->query("SELECT * FROM table WHERE Form_Date = '$date3' AND State = 'HR'");
$numHR3 = $stmtHR3->rowCount();
$stmtHR4 = $db->query("SELECT * FROM table WHERE Form_Date = '$date4' AND State = 'HR'");
$numHR4 = $stmtHR4->rowCount();
“HR”只是其中一个州,我有30个州可以执行这些查询。代码有效,但我想知道是否有更好的方法来做到这一点,如果专家可以帮助我,我将不胜感激。请原谅我,因为我还在学习PHP。
答案 0 :(得分:0)
这可以通过一个查询完成。假设From_Date
字段为DATE
字段类型:
if ($_GET) {
$dateF = date('Y-m-d', strtotime($_GET['datefrom']));
$dateT = date('Y-m-d', strtotime($_GET['dateto']));
$sql = "
SELECT `From_Date`, COUNT(*) AS `count_num`
FROM `table`
WHERE `From_Date` BETWEEN '$dateF' AND '$dateT' AND `State` = 'HR'
GROUP BY `From_Date`
ORDER BY `From_Date` ASC
";
// db fetch all
}
答案 1 :(得分:0)
试试这段代码: 实际上你可以使用数组作为日期
$date = array();
$date[0] = date('Y-m-d', strtotime($datefrom . " +0 days"));
$date[1] = date('Y-m-d', strtotime($datefrom . " +1 days"));
$date[2] = date('Y-m-d', strtotime($datefrom . " +2 days"));
$date[3] = date('Y-m-d', strtotime($datefrom . " +3 days"));
$date[4] = date('Y-m-d', strtotime($datefrom . " +4 days"));
for($i = 0; $i<count($date); $i++{
$query_temp[] = "(
SELECT COUNT(*) FROM table WHERE Form_Date = '" . $date[$i]. "' AND State = 'HR'
) AS count" . $i;
}
$query = "SELECT " . implode(", ",$query_temp);
$stmtHR4 = $db->query($query);
希望这段代码可以解决你的问题