I'm trying to do a simple thing in PHP, but not run properly. So, I need to compare two dates from MYSQL using PHP and show the oldest date, but the result in PHP is not correct.
I have this table in MYSQL DB:
CREATE TABLE users (
id int,
name varchar(255),
date1 date,
date2 date,
);
+---+---------------+------------+------------+
|id |name |date1 |date2 |
+---+---------------+-------------------------+
|1 |ANA |2005-02-27 |2004-03-27 |
+---+---------------+------------+------------+
|2 |MARIA |2010-03-08 |2014-11-01 |
+---+---------------+-------------------------+
I'm using this PHP code:
$conn = mysqli_connect($host, $user, $pwd, $db);
$sql = "SELECT name, UNIX_TIMESTAMP(date1), UNIX_TIMESTAMP(date2) FROM users ";
$result = mysqli_query($conn, $sql);
echo "<html>";
echo "<head>";
echo "</head>";
echo "<body>";
echo "<table border=1>";
echo "<tr>";
echo "<td><b>Name</b></td>";
echo "<td><b>Date1</b></td>";
echo "<td><b>Date2</b></td>";
echo "<td><b>Oldest Date</b></td>";
echo "<tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
if (intval($row[1]) < intval($row[2])){
echo "<td>" . $row[1] . "</td>";
} else {
echo "<td>" . $row[2] . "</td>";
};
};
echo "</tr>";
};
echo "</table>";
It seems easy, but this statement of comparison do not return correctly. I just tried this ways below:
1. Using operator < (no correct return):
if ($row[1] < $row[2]) {...}
2. Using intval to force unix_timestamp to be Integer (no correct return):
if (intval($row[1]) < intval($row[2])) {...}
Any idea to resolv this question? It is a simple comparison of dates (from fields of type DATE in MYSQL).
Thanks