I have been trying to show post from data base according to posted year and month but was unable to do this as i have tried everything i can, but still think this can be done in SQL QUERY and support it in PHP side. Below is my databse structure
id | title | date
-------------------------------------------------
1 | hello this is a post | 2016-01-03 11:33 AM
2 | this is what i think | 2016-01-03 10:33 PM
3 | this is it | 2017-14-06 06:33 PM
4 | Blah Blah Blah | 2017-01-03 10:33 AM
5 | is what i think | 2016-04-03 10:33 PM
Now i want to select and group it this way
Your post on 2016-01-03
hello this is a post
this is what i think Your
post on 2017-14-06
this is it
Your post on 2017-01-03
Blah Blah Blah
Your post on 2017-01-03
is what i think
I tried doing this with bellow code
<?php
//I swear i don't know what else to do here
$db->prepare('SELECT * FROM post
GROUP BY ("")
ORDER BY date');
$db->execute();
$output = $db->getAll();
$db->free();
if(!is_null($output)){
foreach($output as $row){
$title = $row->title;
$date = $row->date;
/*
Only this path i got near but i can only display post for this month using $currentDate below.
But how can i get other once split according to date?
*/
$split = explode(" ", $date);
$currentDate = date('Y-m-d');
if($split[0] == $currentDate){
echo 'post on '.$currentDate.'<br/>'.$title;
}else{
echo 'post on '.$split[0].'<br/>'.$title;
}
?>
You have three requirements here. One is to render the date of a post without the time. The second is to order the posts by date/time.
Those can be done with a query like this.
SELECT DATE(`date`) as date, `title` FROM post ORDER BY `date`
GROUP BY
serves no purpose for this.
The third requirement is to render the date only once when it's the same for consecutive posts. This must be done in php.
$prev_date = "";
foreach ($output as $row) {
$title = $row->title;
$date = $row->date;
if ($date != $prev_date) {
echo "Posts on " .$date;
}
echo information about the post
$prev_date = $date;
}
The trick is to use the variable I've named $prev_date to detect when the date changes from row to row.
My favorite method is always put result into array first.
$date = date('Y-m-d', strtotime($row['date']));
$result[$date][] = $row['title'];
From the array above you can output the result using foreach
.
foreach($result as $key => $value) {
echo 'Your post on '.$key.'<br>';
foreach($value as $k => $v) {
echo $v.'<br>';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.