creating archive for my blog website - php

my database table is something like :
id year month
1 2011 november
2 2011 november
3 2011 october
i need to create a query so it return something like that :
2011
november
november
october
What is the correct query syntax to do it in php script ?
Here is the code i used :
<?php
$uid = $_SESSION['uid'];
$sql = "SELECT year, GROUP_CONCAT(month) AS months FROM articles GROUP BY year";
$res = mysql_query ($sql) or die (mysql_error());
if (mysql_num_rows($res) > 0) {
while ($rows = mysql_fetch_assoc($res)) {
foreach ($rows AS $row) {
echo $row['year'] . "<br>";
$months = explode(",", $row['months']);
foreach ($months AS $m) {
echo $m . "<br>";
}
}
}
}
?>

You can use GROUP_CONCAT() to return a comma-separated list of months:
SELECT year, GROUP_CONCAT(month) AS months GROM tbl GROUP BY year
Returns:
2011 november,november,october
Or just select both columns and handle the display/presentation in your code:
SELECT year, month FROM tbl WHERE year = 2011
Returns
2011 november
2011 november
2011 october
In code, loop and only display the year when it changes.
Update Since a code example seems warranted...
// Results from above GROUP_CONCAT() query already fetched & stored in `$rowset`:
while ($row = mysql_fetch_assoc($res)) {
$rowset[] = $row;
}
// Now $rowset is a 2D array containing all rows.
foreach ($rowset as $row) {
// Output the year
echo $row['year'] . "\n";
// months are comma-separated via GROUP_CONCAT()
// explode them into an array
$months = explode(",", $row['months']);
foreach ($months as $m) {
// Output the months
echo $m . "\n";
}
}

If I understood your question correctly, I think a simple "ORDER BY" clause would do the trick for you, something similar to:
SELECT * FROM table_name ORDER BY year DESC
Then, use your scripting language to display the data, a good idea could be (maybe) to fetch the year of the first row, store it in a temporal variable, then loop through the rows and check if the year has changed, if it has, change the value of the aforementioned variable, something like this:
$current_year = $data_set[0]['year'];
foreach ( $data_set as $data_row )
{
$current_year = ( $data_row['year'] != $current_year) ? $data_row['year'] : $current_year;
//Do something with it and/or the rest of the data
}
Hope this was of any help.
Cheers.

Related

Getting the 3 consecutive year in Query

I have problem getting the year
I have here in my database year of 11/11/2016 - 11/13/2015 - 11/13/2014
the problem is I want to get that year just deducting current year
so if the current year is 2017 I want to get 2016,2015,2014 , and the next year
2018 the year will get is 2017,2016,2015
$selectmemberpaid = mysql_query("SELECT
memberid,StartDate,EndDate,tblpayments.activityname,amount_paid FROM
tblattend_activity LEFT JOIN tblpayments ON tblattend_activity.memberid =
.profile_id WHERE memberid='201400001'");
That is my query..
and this is my while loop
while ($rows = mysql_fetch_assoc($selectmemberpaid)) {
# code...
$dateTimestamp = strtotime($rows['StartDate']);
$year = date("Y", $dateTimestamp);
}
You can get the year from a date string by doing something like this:
$dateTimestamp = strtotime('2015-12-12');
$year = date("Y", $dateTimestamp);
echo $year;
Once you get it you can add or subtract to get the previous/next year (after converting the value into an integer).
I'm not sure I understand what you're asking but:
Query!
$rest = substr(date('d-m-Y'), 6);
$rep = $idz->query("SELECT * FROM stack1 where SUBSTR(date_depart, 6) < $rest
order by SUBSTR(date_depart,6) desc limit 3");
while ($row = $rep->fetch())
{
echo $row['date_depart'];
//echo "<br>";
}
$rep->closeCursor();
Result

Count post article archive by years and months

i need to list total post article archive by years and months like this :
Output(my need):
2014
January(31)
February(28)
March(0)
April(130)
May(450)
June(0)
July(0)
August(0)
September(0)
October(520)
November(20)
December(31)
PHP:
$sql = "SELECT title, YEAR(FROM_UNIXTIME(timestamp)) AS YEAR,
MONTHNAME(FROM_UNIXTIME(timestamp)) AS MONTH,
COUNT(*) AS TOTAL
FROM article GROUP BY YEAR, MONTH ORDER BY YEAR DESC, MONTH ";
$newsdata = DB->fetch($sql);
$currentYear = null;
foreach($newsdata AS $news){
if ($currentYear != $news['YEAR']){
echo '<ul>'.$news['YEAR'].'</ul>';
$currentYear = $news['YEAR'];
}
echo '<li>'.$news['MONTH'].' '.$news['TOTAL'].'</li>';
}
My code worked but print only month if posted article in this month.
Ouput:
2014
January(31)
February(28)
April(130)
May(450)
October(520)
November(20)
December(31)
I need to list all month and print total article for each month. if month not posted article print (0) for this month.
how do can i fix my problem? my code/way is true?!
Your database query won't return a row for a month that has no articles. It doesn't know anything about months. So you need to handle this in code by having an array of all months and looping through that. The alternative would be to alter your schema, have another table with all 12 months, and join on that. But I think the following is easier for you:
$months = array( "January", "February", ... );
Then you can do the following in your output instead:
// Index article counts by month and year for easy lookup
$indexedNewsData = array();
foreach ($newsdata as $news) {
$indexedNewsData[$news['YEAR']][$news['MONTH']] = $news['TOTAL'];
}
// Then print output
foreach($newsdata AS $news){
if ($currentYear != $news['YEAR']){
echo '<ul>'.$news['YEAR'].'</ul>';
$currentYear = $news['YEAR'];
} else {
// Continue here otherwise we will print each year's data 12x
continue;
}
foreach ($months as $month) {
$total = intval($indexedNewsData[$news['YEAR']][$month]);
echo '<li>'.$month.' '.$total.'</li>';
}
}

My loop is doubling the results when match is found

I have a database with some months. I am using the following to group similar months:
$Mydates = array();
while(........)
{
$date = $row['date'];
$Mydates[$date] = (isset($Mydates[$date])) ? $Mydates[$date] + 1: 1;
}
My table contains 4 data, 3 Jan's and 1 Feb. Now this information is being run through an array which contains the months of the year. Here is what I have so far:
$months = array("Jan","Feb","Mar",etc........);
foreach($months as $month)
{
foreach($Mydates as $Mydate => $Number)
{
if($month == $Mydate)
{
echo $month." (".$Number.")<br />";
}else{
echo $month."<br />";
}
}
}
Now when there were only Jan's this works fine. Now that I have added another month my results display like below:
Jan(3)
Jan(3)
Feb(1)
Feb(1)
Mar
Mar
etc.....
etc.....
How can I get this to only display once like this:
Jan(3)
Feb(1)
Mar
etc....
Now I have noticed that the more months add the more it duplicates. Can someone look at this and tell me where I am going wrong here?
It seems, $Mydates is already aggregated and accessible by month. Remove the inner loop and just look, if there's a corresponding month in $Mydates
foreach($months as $month) {
if(isset($Mydates[$month])) {
echo $month." (".$Mydates[$month].")<br />";
} else {
echo $month."<br />";
}
}

Finding Distinct Month

I make a page, that display records from database,in group of 10 records per page using paginition concept,
i wanna print Like: Month name/Year.
That month and year is distinct form that page means of 10 records.
Suppose page number 10 contains 10 records with 3 distinct month named Dec 2011 , Jan 2012 and, March 2012,
In this case i want to print Month: Dec/2011 ,Jan,March/2012
Thanks in advance..
If your date is stored like you write it: Dec 2011, Jan 2012 then you should do like this
$arr = array();
$sql = mysql_query(__YOUR_SQL__);
while($row = mysql_fetch_array($sql)) {
$date = explode(" ", $row['date']);
if(!array_key_exists($date[1], $arr))
$arr[$date[1]] = array();
array_push($arr[$date[1]], $date[0]);
}
foreach($arr as $key => $value) {
if(count($value) == 1)
echo $value[0] . '/' . $key;
else
echo implode(", ", $value) . ' ' . $key;
}

Hierarchically sorted MySQL output with PHP

I'm revising the navigation of my news system and would like to do so using minimal MySQL queries. I've managed to get it all down to one query, but something seems to be wrong. Any help would be greatly appreciated.
What I wish to achieve is (literally) the following overview of events, hierarchically sorted per year and month, along with the number of events in that month:
2012
--04 (3)
--02 (1)
--01 (1)
2011
--12 (3)
--11 (2)
--10 (3)
--09 (1)
--07 (1)
--02 (1)
I'm very close. My query is as follows:
SELECT start_date, date_format(start_date, "%Y") as year, date_format(start_date, "%m") as month FROM event ORDER BY start_date desc
Then, my PHP loop is as follows:
$year = '';
$year_counter = 0;
$month = '';
$month_counter = 1;
while($row = mysql_fetch_assoc($result)){
if ( $year != $row['year'] ) {
$year = $row['year'];
$output .= $year.'<br />';
}
if ( $month == $row['month'] ) {
$month_counter++;
} else {
$month = $row['month'];
$output .= '--'.$month.' ('.$month_counter.')<br />';
$month_counter = 1;
}
}
Which generates everything perfectly, except for the number of events per month, that seem to be always one line off (you please see the difference with the wanted result above).
2012
--04 (1)
--02 (3)
--01 (1)
2011
--12 (1)
--11 (3)
--10 (2)
--09 (3)
--07 (1)
--02 (1)
I've been tinkering with this all afternoon without success. I think it's best to leave it to the absolute experts. A hand please?
Currently, you're printing the month_counter before you've updated it for the next month. Before your while loop, you need to initialize your variables based on the first row retrieved rather than the default values.
if ($row = mysql_fetch_assoc($result){
$year = $row['year'];
$month = $row['month'];
$month_counter = 1; //1 because you've already counted the first article
// print out the first year
$output .= $year.'<br />';
while($row = mysql_fetch_assoc($result){
if ( $year != $row['year'] ) {
$year = $row['year'];
$output .= $year.'<br />';
}
if ( $month == $row['month'] ) {
// You've found one more article for this month, so increment the count
$month_counter++;
} else {
// You've hit a new month, so print out the information you collected
// about the previous month
$output .= '--'.$month.' ('.$month_counter.')<br />';
$month = $row['month'];
$month_counter = 1;
}
}
}
The difference between outputting the year and outputting the month, is that you also want to output the count associated with the month, whereas there is no additional information associated with the year. You have to print that before you change to the next month.
Your
$month = $row['month'];
is in the wrong place. It sets the $month-variable for a new month, but it has been counting the number for the months before it.
The first time it runs through the while-loop
if ( $month == $row['month'] )
can never be true, so it goes into the else-statement, displaying the month and the count (which is 1 because you set it to 1 at the top)...
I probably made some mistake here, but you could count events per Year-month and group them accordingly.. something like
SELECT start_date, date_format(start_date, "%Y") as year, date_format(start_date, "%m") as month, date_format(start_date, "%Y%m") gr, COUNT(id)
FROM event
ORDER BY start_date desc
GROUP BY gr

Categories