简体   繁体   中英

creating archive for my blog website

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM