I have data coming back from a query. It could be a join or just a simple table selecting everything. I would like the data to be presented in descending order of date. And
";
try {
$mysqli= new mysqli('hostname', 'dbuser', 'password', 'dbname');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
// your query can be a join. No difference. Just plug yours in and tweak everywhere as necessary
$query = "select ayr,otherStuff from myTable123 order by ayr desc";
// The following variable is used to pick up a "year change" while processing the data to segment tables
$curYear="^^junk^^"; // so set it to junk first, so first time in is a change
$bOneYet=false; // has there been any output at all yet. I mean anything? So far, no
if(!$result = $mysqli->query($query)){
die('There was an error running the query [' . $mysqli->error . ']');
}
while ($row = $result->fetch_assoc()) {
if ($row['ayr']!=$curYear) {
// the year has changed (including the first time in this while)
if (!$bOneYet) {
$bOneYet=true; // will one get in here once
}
else {
// must end previous table
echo "";
}
// regardless, we need a new table
echo "
The Year The other thing ";
}
echo "" . $row['ayr'] . " " . $row['otherStuff'] . " ";
$curYear=$row['ayr']; // kind of important. Facilitates subsequent year table segments
}
echo "
"; // close up the last dangling table
$result->free();
$mysqli->close();
}
catch (mysqli_sql_exception $e) {
throw $e;
}
Hopefully the source code comments are sufficient in-line to describe the way the years are segmented by tables. Focus on variable $curYear which picks up that change as the data is processed, descending, by year.
The variable $bOneYet is false only one time through the loop. The rational is that when a year change occurs, is written out, except for the first time through.
Don't forget the importance of error reporting as seen at the top of the code. And steer toward mysqli or pdo.
Display errors for test and staging, never production.