How to only echo a value from MySQL once with PHP loop

767

MySQL table is set up like this:

id | year | name | filename | category | description

Currently, my PHP is this:

while($row = mysql_fetch_array($result)) {
    $yr = $row["year"]; 
    $nm = str_replace('"', '', $row["name"]);
    $fn = $row["filename"];
    $cat = $row["category"];
    $desc = str_replace('"', '', $row["description"]);
    echo "<year id=\"$yr\">\r\n";
    echo "<entry id=\"$nm\" filename=\"$fn\" category=\"$cat\" description=\"$desc\">\r\n";
    echo "</entry></year>\r\n";
}

This spits out a year for every entry. I only want the year to echo one time and then list every name for that year.

447

Answer

Solution:

I have simplified your code for the purpose of this answer. You can use a PHP if statement to check if the year is still the same, or if the year has changed.

To use this, make sure your SQL query sorts the results by year

$oldyr = ""; //Initiate olodyr variable


while(...){ //The loop used to fetch
   $yr = $row["year"];

   if(!($yr === $oldyr)){ //The year has changed, so close the old one and open a new one
      echo('</year>');

      echo "<year id='$yr'>\r\n";
      $oldyr = $yr;
   }
//Print other data, such as names

}

Also, try to use mysqli, as mysql is deprecated, as you can see here.

People are also looking for solutions to the problem: php - index array results from mysql call so I can call multiple times

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.