运行脚本时出现此错误:在布尔值上调用成员函数fetch_assoc()。这让我发疯了。
我从输入框中获取数据如下:2017-12-14 06:42:10
$sql = "SELECT count(*) as total FROM `purchase` where purchase_datetime BETWEEN str_to_date($date1, 'Y-m-d H:i:s') and str_to_date($date2, 'Y-m-d H:i:s')";
或
$sql = "SELECT count(*) as total FROM `purchase` where purchase_datetime BETWEEN '$date1' and '$date2'";
或
试着这个:
$date1 = date('Y-m-d H:i:s', $date1);
$date2 = date('Y-m-d H:i:s', $date2);
完整代码:
<?php
if (isset($_POST['submit']) && isset($_POST['date1']) && isset($_POST['date2'])) {
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$date1 = date('Y-m-d H:i:s', $date1);
$date2 = date('Y-m-d H:i:s', $date2);
$sql = "SELECT count(*) as total FROM `purchase` where purchase_datetime BETWEEN '$date1' and '$date2'";
$query_result = $conn->query($sql);
$rows = $query_result->fetch_assoc();
echo "Result is: " . $rows['total'] . " purchases";
}
?>
答案 0 :(得分:0)
date
功能是格式化今天的日期,而不是给定日期。使用DateTime::format
函数格式化给定日期。试试这个:
$date1 = $date1->format('Y-m-d H:i:s');
$date2 = $date2->format('Y-m-d H:i:s');
$sql = "SELECT COUNT(*) AS total FROM purchase WHERE purchase_datetime BETWEEN '$date1' AND '$date2';";
或者,您可以使用date_format
别名功能,如下所示:
$date1 = date_format($date1, 'Y-m-d H:i:s');
$date2 = date_format($date2, 'Y-m-d H:i:s');
$sql = "SELECT COUNT(*) AS total FROM purchase WHERE purchase_datetime BETWEEN '$date1' AND '$date2';";
答案 1 :(得分:0)
确保您的格式为:
$date1=$_POST['date1']//1496620800;
$date2=$_POST['date2']//1496707200;
$date1 = date('Y-m-d', $date1);//2017-06-05
$date2 = date('Y-m-d', $date2);//2017-06-06
purchase_datetime格式:2017-xx-xx