简体   繁体   English

如何在mysql中选择日期范围?

[英]How to select date range in mysql?

i want to select a date range in mysql. 我想在mysql中选择一个日期范围。

$dateFrom='2016-01-01';
$dateTo='2016-01-02';

NOT WORKING 不工作

query ="SELECT ".$name.",timestamp FROM people where age=".$age." AND timestamp>=".$dateFrom." AND timestamp<.$dateTo";

WORKING 工作中

query ="SELECT ".$name.",timestamp FROM people where age=".$age." AND timestamp>='2016-01-01' AND timestamp<'2016-01-02';

You will need to put ' single quotes arround dates variable. 您需要将'单引号括起来日期变量。

query ="SELECT ".$name.",timestamp FROM people where age=".$age." AND timestamp>='".$dateFrom."' AND timestamp<'".$dateTo."';

Make sure you're open to SQL injection attacks, you should better use Prepared statements to avoid the same. 确保对SQL注入攻击开放,最好使用Prepared语句来避免这种情况。

In situations like these, it's often a good idea to just print out the SQL that you have generated. 在这种情况下,通常最好只打印出您生成的SQL。 For your failing code you will get something like this: 对于失败的代码,您将获得以下内容:

SELECT some_name,timestamp
FROM people where age=40
AND timestamp>=2016-01-01
AND timestamp<2016-01-02

See the timestamps? 看到时间戳了吗? They are unquoted strings. 它们是未引用的字符串。 The SQL compiler will probably try to do some kind of subtraction there (2016 - 1 - 1). SQL编译器可能会在那里尝试进行某种减法运算(2016-1-1)。

As Alok Patel has pointed out , one solution is to change your code to put quote characters around your dates. 正如Alok Patel 指出的那样 ,一种解决方案是更改代码以在日期周围加上引号字符。 Another solution is to treat your dates as numbers, as numbers don't need to be quoted and MySQL is quite happy to use a date in the format 20160101 as a number. 另一种解决方案是将日期视为数字,因为不需要将数字引起来,并且MySQL非常乐意将格式为20160101的日期用作数字。

But I have to reiterate what other people have said. 但是我必须重申其他人的意见。 Interpolating user input into an SQL string is a very bad idea . 将用户输入内插到SQL字符串中是一个非常糟糕的主意 Please don't do that! 请不要那样做!

"SELECT ".$name.",timestamp 
FROM people WHEREage=".$age." 
AND timestamp BETWEEN'".$datefrom."' AND'".$dateTo."'

Check the difference. 检查差异。

Your code: 您的代码:

query ="SELECT ".$name.",timestamp FROM people where age=".$age." AND timestamp>=".$dateFrom." AND timestamp<.$dateTo";

Updated code: 更新的代码:

query ="SELECT ".$name.",timestamp FROM people where age=".$age." AND timestamp>='".$dateFrom."' AND timestamp<'".$dateTo."';

You've a sintax error on your (not working) code. 您的(无效)代码上出现sintax错误

You can use sprintf function - http://php.net/manual/en/function.sprintf.php - to concat strings; 您可以使用sprintf函数-http ://php.net/manual/zh/function.sprintf.php-连接字符串;

Live demo: http://ideone.com/8uWe6R 现场演示: http//ideone.com/8uWe6R

使用sprintf格式化SQL查询的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM