我在php数据对象中使用'BETWEEN'语句来显示在2个特定日期之间发布的帖子,但是,'date from'不起作用,尽管'date to'工作正常,如果我只设置'date从',没有显示,但如果我只设置'日期',显示正确的帖子,如果我设置'日期从'和'日期到',仍然显示正确的帖子,问题是只有当我选择只是'约会',这是我的代码
$dateFrom = $_POST['dateFrom'];
$dateTo = $_POST['dateTo'];
$sql = "SELECT * FROM Main_Posts_table WHERE DATE(time) BETWEEN '$dateFrom' AND '$dateTo' ";
$data = $connect->query($sql);
echo "<center><table class = 'main_table'>";
foreach($data as $row){
echo "<tr><td><span id = 'time_of_post'>".$row['time']."</span><br/><br/>".$row['posts']."<br/><br/><span id = 'comment_button'>comments ↡</span></td></tr>";
}
echo "</table></center>";
答案 0 :(得分:0)
以下代码有效:
if(empty($_POST['dateTo']) && !empty($_POST['dateFrom'])){
$sql = "SELECT * FROM Main_Posts_table WHERE DATE(time) BETWEEN '$dateFrom' AND '2080-12-31' ";
}
else{
$sql = "SELECT * FROM Main_Posts_table WHERE DATE(time) BETWEEN '$dateFrom' AND '$dateTo' ";
}
如果没有设置dateto,它被设置为null,一个小于datefrom的值,所以我创建了一个单独的if else块,以检查只设置了datefrom的情况,然后我将dateto设置为一个非常高的价值,如果有人能想到更短的代码,请发布