从MYSQL获取日期范围内的记录-PHP

时间:2018-07-30 09:52:09

标签: php mysql

我下面有一个MYSQL表,我正在尝试检索特定日期之间的记录数。

我遇到以下错误:

  

“试图在第18行的/var/www/html/dev/timeTest.php中获取非对象的属性'num_rows'

MySQL表的日期列:

enter image description here

PHP:

 $date1 = '2018-07-01';
 $date2 = '2018-07-30';

 $sql = "SELECT * FROM scanUploads WHERE dateUpload BETWEEN {$date1} AND {$date2}";
 $result = $mysqli -> query($sql);
 $count = $result -> num_rows; // LINE 18
 echo 'records: '.$count;

2 个答案:

答案 0 :(得分:2)

$date1 = '2018-07-01';
 $date1 = '2018-07-30';

 $sql = "SELECT * FROM scanUploads WHERE 
DATE_FORMAT(dateUpload,'%Y-%m-%d') >= '".$date1."' AND DATE_FORMAT(dateUpload,'%Y-%m-%d') <= '".$date2."' ";
 $result = $mysqli -> query($sql);
 $count = $result -> num_rows; // LINE 18
 echo 'records: '.$count;

答案 1 :(得分:2)

您缺少引号,这会破坏语法。

大括号对我来说也很奇怪。

有两种方式来表达它,或者使用'"来分隔查询字符串:

$sql = 'SELECT * FROM scanUploads WHERE dateUpload BETWEEN "'.$date1.'" AND "'.$date2.'"';
$sql = "SELECT * FROM scanUploads WHERE dateUpload BETWEEN \"$date1\" AND \"$date2\"";

// whenever wondering about the validity of generated SQL:
// die($sql);

// and whenever wondering about the result-set returned:
// die(print_r($result, true));

转义的双引号\"将始终按字面处理,但仅在" "双引号内。