Between子句返回0条记录


Between clause is returning 0 records

我在数据库中有3条记录符合条件,但当我使用between子句运行查询时,它得到了0条记录。

$current_date  = date('m-d-Y', strtotime('monday this week'));
$upcoming_date = date('m-d-Y', strtotime('monday next week'));
$sql   = mysqli_query($connection, "SELECT * FROM result WHERE test_date BETWEEN $current_date AND $upcoming_date AND login = '".$_SESSION['uid'] ."'");
$total_check = mysqli_num_rows($sql);

这是我的数据库

result_id`, `login`, `test_id`, `test_date`, 
(1,           '2',      6,      '08-03-2016', 
(2,           '2',      5,      '08-03-2016', 
(3,           '2',      3,      '08-03-2016',

请让我知道我在哪里做错了什么,因为我得到了0个结果,$_SESSION['uid']是2

您应该将'用于$current_date和$upcoming_date

"SELECT * FROM result WHERE test_date BETWEEN '$current_date' AND '$upcoming_date' AND login = '".$_SESSION['uid'] ."'"

使用如下prepare语句来避免SQL注入

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

如果您想在范围搜索(如BETWEEN)中使用日期,则会错误地存储日期。必须将它们存储在DATE列中。将它们存储在VARCHAR()列中是个坏主意。

您可以使用类似的方法,使用STR_TO_DATE()来处理您的错误签名表。

 $current_date  = date('Y-m-d', strtotime('monday this week'));
 $upcoming_date = date('Y-m-d', strtotime('monday next week'));
 $sql = mysqli_query($connection, "SELECT * FROM result WHERE STR_TO_DATE(test_date,'%d-%m-%Y') BETWEEN '$current_date' AND '$upcoming_date' AND login = '".$_SESSION['uid'] ."'");

要求MySQL比较字符串01-01-201612-31-2015,并确定后者在前者之前是不合理的。字符串比较是词汇性的。但2015-12-31明显早于2016-01-01

这有点棘手,因为文本字符串08-08-2016确实在08-15-2016之前,这是偶然的。但到了年底,一切都崩溃了。