Here's my PHP/SQL Request
<?php $events = $wpdb->get_results(
"
SELECT *
FROM `wp_em_events`
LIMIT 5
// HERE'S MY ORDER BY DATE
"
);
$dt = new DateTime($event->event_start_date);
$formattedDate = $dt->format('d M Y');
foreach ( $events as $event )
{
echo '<div class="home-event">';
echo $formattedDate;
echo $event->event_name;
echo '</div>';
}
?>
According to a table containaing a column "event_start_date" where values looks like these :
2013-03-27
2013-04-03
2013-03-31
I want to order my events by those date (the closest to us first)
I tried a single
ORDER BY event_start_date DESC
But it "burn" my request
------- BONUS QUESTION --------
How could I increment my events in order to have :
<div class="home-event-1">
<div class="home-event-2">
<div class="home-event-3">
...
Thank you very much !!
The ORDER BY
comes before the LIMIT
. You'll want:
SELECT
*
FROM
`wp_em_events`
ORDER BY
event_start_date DESC
LIMIT 5
Also, you're fetching the date in the wrong place. It'll need to be within the iteration:
foreach ( $events as $event )
{
$dt = new DateTime($event->event_start_date);
$formattedDate = $dt->format('d M Y');
// ...
As for the increments:
foreach ( $events as $key => $event )
{
echo '<div class="home-event-' . ($key + 1) . '">';
echo $formattedDate;
echo $event->event_name;
echo '</div>';
}
Assuming $events
is not an associate array, of course. If it is:
$i = 0;
foreach ( $events as $event )
{
echo '<div class="home-event-' . ++$i . '">';
echo $formattedDate;
echo $event->event_name;
echo '</div>';
}