Sunday, 18 August 2013

weird issue when sorting MySQL `date` results

weird issue when sorting MySQL `date` results

I'm getting some weird results when I query on of my tables to show
upcoming birthdays (schema and query below), and then sort by date with
the upcoming dates first. The type for the dob (date of birth) field is
date with the format 0000-00-00
I'm using the below schema:
People:
+------------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra
|
+------------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL |
auto_increment |
| fname | varchar(32) | NO | | NULL |
|
| lname | varchar(32) | NO | | NULL |
|
| dob | date | NO | | 0000-00-00 |
|
| license_no | varchar(24) | NO | | NULL |
|
| date_added | timestamp | NO | | CURRENT_TIMESTAMP |
|
| status | varchar(8) | NO | | Allow |
|
+------------+-------------+------+-----+-------------------+----------------+
and here's my query, as it's called from PHP:
<?php
/* This will give us upcoming dobs for the next 2 weeks */
$con = connect_db();
// grab any dobs coming up in the next week and sort them by what's
//coming up first
//if they are born on Feb. 29th, it will fall on March 1st
$query = 'select p.lname, p.fname, u.number, p.dob ' .
'from people p, units u where p.id = u.resident and ' .
'DAYOFYEAR(curdate()) <= DAYOFYEAR(DATE_ADD(dob, INTERVAL ' .
'(YEAR(NOW()) - YEAR(dob)) YEAR)) AND DAYOFYEAR(curdate()) +30 >=
' .
'dayofyear(`dob`) order by dayofyear(dob) limit 7;';
$result = mysqli_query($con, $query);
if (!empty($result)) {
while($row = mysqli_fetch_array($result)) {
$fname = $row['fname'];
$lname = $row['lname'];
$number = $row['number'];
$dob = date("m-d", strtotime($row['dob']));
if($dob == date("m-d")) {
$dob = 'Today!';
printf('%s, %s</br>Unit: %s</br>%s</br></br>',
$lname,
$fname, $number, $dob);
} else {
printf('%s, %s</br>Unit: %s</br>Date:
%s</br></br>', $lname,
$fname, $number, $dob);
}
}
}
?>
here's an example of the returned query:
Name, Name
Unit: 110
Date: 09-11
Name2, Name2
Unit: 434
Date: 09-10
As you can see, the order is wrong!
EDIT - Now I've noticed that the records in question (the two dates above)
are not ordered correctly ever in MySQL!
One of the full dates is: 1950-09-11 and the other is: 1956-09-10
I've looked through those two records and haven't found any mangled data,
so I'm pretty confused as to why this is happening

No comments:

Post a Comment