I am trying to modify my existing code that returns from DB the rows that are between a specific date and time. It does the job right, but I would like to add a feature as described below.
This is an example of my DB
start end
1st row 2012-07-24 18:00:00 2012-07-28 17:00:00
2nd row 2012-07-25 19:00:00 2012-07-30 19:00:00
3rd row 2012-07-25 22:00:00 2012-07-28 13:00:00
4th row 2012-07-25 23:40:00 2012-07-27 18:00:00
...
...
...
When my input is 2012-07-25 23:00:00 BETWEEN start AND end ORDER by start DESC
So the results are,
3rd row
2nd row
1st row
Until here everything is great. However, I want to list any rows that are going to begin in the next 2 hours at the top of the list.
This is row number 4.
I tried to do it using
ABS(TIMESTAMPDIFF( HOUR , `start`, :time )) < 2
unfortunately, I can’t find the solution.
Below is my code since now, any help is appreciated. ( I use 3 variables, selected, city and type)
// Store where clauses and values in arrays
$values = $where = array();
if (!empty($selected)) { //
$where[] = ':selected BETWEEN `start` AND `end`';
$values[':selected'] = $selected;
}
if (!empty($city)) { //
$where[] = '`city` = :city';
$values[':city'] = $city;
}
if (!empty($type)) { //
$where[] = '`type` = :type';
$values[':type'] = $type;
}
// Build query
$question = 'SELECT * FROM `events`';
if (!empty($where)) {
$question .= ' WHERE '.implode(' AND ', $where);
$question .= ' ORDER BY `start` DESC';
}
$query = $db->prepare($question);
$query->execute($values);
I didn’t check the order of your arguments, so I got the condition backwards. However, my initial statement still stands. Basically, the simplest answer is to adjust your starting time, like so:
And have a working example.