简体   繁体   中英

How do I SELECT rows using DATEDIFF?

I'm using this calendar plugin to display my client's agenda using a mySQL db. The calendar POSTs a request to my script with a start and end UNIX timestamp like this:

/getevents.php?start=1262332800&end=1265011200&_=1263178646
//That last piece of data is to prevent caching.. apparently

In my script, I convert the UNIX timestamps to mySQL datetime objects like this:

$start = $_GET['start'];
$end = $_GET['end'];
$start = gmdate("Y-m-d H:i:s", $start);
$end = gmdate("Y-m-d H:i:s", $end);
printf($start.".....".$end);

This correctly prints something like the following (when I navigate to September 2012):

2012-08-26 04:00:00.....2012-10-07 04:00:00

Now I want to select all events from my database that fall between those dates. My database has only 1 row, and the start field is today's date:

 id     start                   end
 10     2012-09-05 20:27:00     0000-00-00 00:00:00

But with the following SQL statement, I don't get a result. I've tried inverting the > to < just for the hell of it, but still nothing. I'm not getting any errors at all, just no results.

$sql = "SELECT * FROM all_events WHERE DATEDIFF('$start', 'start') > 0";
$result = mysql_query($sql, $link) or die(mysql_error());
echo "Rows:".mysql_num_rows($result);

As you can see, right now I'm just checking that the start of the event is greater than the start of the calendar's date range.. ie August 26th is the start for the month of September.

I don't see anything wrong... help please! I'm tearing my hair out!

不要对列名使用single quotes ,而是使用backticks .try

SELECT * FROM all_events WHERE DATEDIFF(`start`, '$start') > 0

I would recommend to use FROM_UNIXTIME and prepared statements like so:

$stmt = $mysqli->prepare("SELECT * FROM all_events WHERE DATEDIFF(FROM_UNIXTIME(?), start) > 0"); 
$stmt->bind_param($_GET['start']);

mysql_ functions are being deprecated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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