PHP MySQL date ordering - php

Ok im trying to order results by date and time in an ascending order but so far this isnt working :(
$kalendarquery = mysqli_query($con, "SELECT
people.firstname,
people.lastname,
people.id,
people.avatar,
dates.date,
dates.time,
dates.timezonedate
FROM people
INNER JOIN dates ON
people.id=dates.invited_id
WHERE dates.inviter_id='$user_id' AND status='1'
ORDER BY STR_TO_DATE(CONCAT(dates.date,' ',dates.time), '%d/%m/%y %h:%m') ASC
LIMIT 50");
I mean it doesnt order it by the lowest date to the biggest

Your second parameter to STR_TO_DATE has to match the date format in your char field; otherwise, the conversion will just return NULL for every row which is why its not being ordered.
So since your dates are formatted like 27.03.2015 using . as delimeter, you need to make sure you use . in that parameter rather than /.
Also lower case %y is for 2-digit year, so you need %Y because you're using 4-digits:
ORDER BY STR_TO_DATE(CONCAT(dates.date,' ',dates.time), '%d.%m.%Y %h:%i') ASC
You didn't give an example of your time format, but you can figure out how to do it properly by reading the docs for date_format(). But notice above I changed %m to %i in the time part: you were using %m for both month and minutes which is obviously wrong.

Related

Formatting a DateTime column in PHP

I have a column that stores DateTime in a MySQL database. I want to compare the Date part (and not the time) to the current day. I am not sure what method to use as I am very new to PHP.
$today=date("Y-m-d");
$sql="SELECT journey_id FROM tbl_journeys WHERE identity='$driver_id' AND DATE_FORMAT(`date`, '%Y %m %d')='$today'";
I tried this way but it's not working. In the statement, date is a column in the table which I need to trim to only Year-month-day
You're using different characters between the year, month, and day in the two formats.
$today=date("Y-m-d");
puts hyphens between them, while
DATE_FORMAT(`date`, '%Y %m %d')
puts spaces between them.
Change one of them to match the other, e.g.
DATE_FORMAT(`date`, '%Y-%m-%d')
Or you could just do it all in MySQL:
$sql="SELECT journey_id FROM tbl_journeys
WHERE identity='$driver_id' AND DATE(`date`) = TODAY()";

Select next event

I would like to select the next event from my table. the date of the event is stored as a VARCHAR in the format Y-m-d in a column called date.
But i am unsure how to compare VARCHARS/strings in sql. I tried the following but it gives me an event in the past.
$d = date("Y-m-d");
mysql_query("SELECT * FROM events WHERE date>$d ORDER BY date ASC LIMIT 1,1");
You haven't quoted your date string, so your query will be literally somethign like
... AND date > 2014-04-11 ORDER ...
Since there's no quotes, MySQL is free to interpret your date as a simple mathematical subtraction, and you end up doing
... AND date > 1999 ORDER ...
Try
... AND date > curdate() ...
instead. There's no point in having PHP generate a date and passing it into mysql, when mysql can generate that date perfectly well on its own.
As well, having PHP generate the date can lead to race conditions. E.g. PHP generates "today 11:59:59pm", but mysql actually executes as "tomorrow 00:00am". Maybe not relevant to you, but in banking "overnight run" code, this could cost someone literally millions of dollars.
SELECT * FROM events WHERE active=1 AND DATEDIFF(date, CURDATE()) >= 0 ORDER BY date ASC LIMIT 1,1;
This will select the next event inclusive of today's events. IF you do not want to include today's events, change >= to >
sqlfiddle: http://sqlfiddle.com/#!2/f205a3/9

How to count and display number of rows in database with the same date (PHP)

I have a database that contains three different columns: domain, date, length (in that order). What I'm trying to do is count the occurrence of every unique date in the database without knowing what the end date is in the database. The start date is always todays date.
So far I've only been able to count the occurences of a specific date, which requires me to put in an exact date.
What I want the PHP script to do is to start with todays date and output the number of times the date is mentioned (or the number of rows with that date) and then continue until it reaches a date that doesn't have a value (you could call this the end date).
I'm surprised and frustrated that I haven't been able to find the solution yet. It seems like a very easy thing to do.
I'd be super happy for any hints, tips or solutions.
Use a combination of a GROUP and WHERE clause.
SELECT COUNT(*) AS `occurrences`, `date` FROM `table` WHERE `date` >= CURDATE() GROUP BY `date`
Use group by and order by
SELECT dateCol, Count(*) FROM myTable
WHERE dateCol >= date(now())
GROUP BY dateCol
ORDER BY dateCol ASC
Edit: SQLFiddle with your example: http://www.sqlfiddle.com/#!2/5e86b/2

MySQL entries sorted by date in wrong order

Using a MySQL SELECT query via PHP, I would like to order my entries by date. The query I'm using is:
$query = "SELECT title, file, oblong_pic, square_pic,
DATE_FORMAT(date, '%W %d %M %Y') AS date
FROM dyhamb ORDER BY date DESC";
I have four entries dated: 24/7/2012, 1/7/2012, 5/6/2012 and 10/4/2012 and would like them to be displayed in that order however they are being displayed as: 24/7/2012, 10/4/2010, 5/6/2012 and 1/7/2012.
I can only think that I've set my query up incorrectly somehow but I don't see where I've gone wrong.
%W in DATE_FORMAT is weekday name, so sort starts with that
If you want to use date alias you should rewrite your sql query to:
$query = "SELECT title, file, oblong_pic, square_pic, date AS sort_date,
DATE_FORMAT(date, '%W %d %M %Y') AS date
FROM dyhamb ORDER BY sort_date DESC";
You have defined a column alias with the same name with an existing column. Thus the ordering occurs based on the DATE_FORMAT function, instead of the date real value.
As a good practice, I suggest to remove the DATE_FORMAT function from the mysql query and leave this part to your php script.
DATE_FORMAT returns string, therefore you are ordering it as string, in which you are using %W, so you are ordering firstly by weekday name. If you want to order by date then just do this:
SELECT title, file, oblong_pic, square_pic, date
FROM dyhamb
ORDER BY date DESC
If you really want to select formated date then add DATE_FORMAT(date, '%W %d %M %Y') as formatted_date to selected columns, note that column alias is not date but formatted_date.

Sorting through a Database query for all rows created in the same day Unix Timestamp in PHP

I am developing a PHP application which will handling many company articles.
Now I am creating a page which should order articles BY DATE ie all articles created in a certain day are shown with the appropriate heading and so on for all the articles.
I have used Unix timestamps to save the dates in the MySql db but I cant find code which only sorts dates by days. Can I please get some assistance.
Thanx
You can use mktime() to get the timestamps you would want to use to bin the entries:
http://us.php.net/manual/en/function.mktime.php
$timestamp_for_my_birthday = mktime(0,0,0,10,16,1984);
$timestamp_for_the_next_day = mktime(0,0,0,10,17,1984);
if($time > $timestamp_for_my_birthday && $time < $timestamp_for_the_next_day){
// Time is on my birthday
}
To make this into a MySQL query:
$SQL = "SELECT * FROM dates WHERE date > $timestamp_for_my_birthday AND date < $timestamp_for_the_next_day;";
To order by date I think it would go something like:
SELECT * FROM dates ORDER BY FROM_UNIXTIME(time, '%M %d %Y');
Can you do a
SELECT DATE(FROM_UNIXTIME(my_field_name)) FROM table_x ORDER BY my_field_name
You can order by the timestamp column, but if you want a string representation of which day the record belongs to, you can get any part of the date with the FROM_UNIXTIME(timestamp, 'format') function.
select FROM_UNIXTIME(timestampColumn, '%Y %m %d')
The format values in the second parameter can be adjusted based on the table here:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

Categories