如何使用表单将SQL查询更改为仅显示特定范围之间的注册日期?
问题描述:
下面的代码是我到目前为止,如果任何人有任何BETWEEN的工作知识,并可以指向我在正确的方向,我真的很感激它。如何使用表单将SQL查询更改为仅显示特定范围之间的注册日期?
<form action="index.php" method="GET">
Starting from:<br>
<input type="date" name="startDate" ><br><br>
Upto:<br>
<input type="date" name="uptoDate" ><br><br>
<input type="submit">
</form>
<?php
// I removed the connection details for obvious reasons
// It does connect and display the data with no problems
$startingFrom = $_GET[startDate];
$upto = $_GET[uptoDate];
// I tried this but it does not seem to work
// $query = "SELECT * FROM table BETWEEN $startingFrom AND $upto";
$query = "SELECT * FROM table";
$result = mysql_query($query);
echo "<table><th>Name</th><th>Registered Date</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['registered'] . "</td></tr>";
}
echo "</table>";
mysql_close();
?>
答
如果要返回给定的两个日期之间的效果,请使用此代码
SELECT *
FROM table
WHERE date BETWEEN CAST('2015-04-03' AS DATE) AND CAST('2015-05-28' AS
DATE);
与日期之间,你需要使用CAST()到将该值转换为适当的数据类型,如DATE或DATETIME。如果您正在使用之间,DATETIME您的值转换为DATETIME:
SELECT *
FROM table
WHERE date BETWEEN CAST('2015-04-03 08:40:09' AS DATETIME) AND CAST('2015-05-28 02:50:09' AS DATETIME);
作为一个侧面说明,使用MySQL提高扩展(mysqli的),你都忘记关闭您的输入字段这是不是一个很好的代码。
+0
非常感谢Saral!这解决了问题:) – Aaron
答
您的查询应该是:
select * from table where registered >= $startDate and registered <= $endDate;
+0
我刚刚尝试了您的建议,但似乎没有奏效。是否因为此代码所在的文件是index.php,而表单操作是index.php。我认为这只是简单地重新加载页面? – Aaron
你只是想''哪里',它应该是'SELECT * FROM'表'其中'列'之间的$ startingFrom和$ upto' – Rence
好点!我改变了它,但由于某种原因,它仍然不起作用。难道是因为格式为06/07/2017,而我的数据库中是2017-07-17? – Aaron