问题
I have a menu for a website that I am pulling all of the information from a mySQL database. I am trying to find a way to sort the food into categories with headings.
They would be sorted like
Appetizers:
- Results display here
Salads:
- Results display here
And so on for a couple different categories. Here is my select statement
$sql = "SELECT item, price, description, category, picture, category_id FROM menu ORDER BY category ASC"; $new_result = mysql_query($sql);
And this is how I am importing the data using php
<?php while($new_row = mysql_fetch_array($new_result)) {
if (isset($new_row["picture"])){
echo "<div class='images'><img style='margin:15px;' src='".$new_row['picture']."' alt='".$new_row["item"]."' />
<h2>". $new_row['item']."</h2>
<h4>Price: ". $new_row['price']. " </h4>
<p>Description: ". $new_row['description'] ."</p>
<p>Category: ". $new_row['category'] ."</p></div>";}
else {
echo "<div class='images'><img style='margin:10px;' src='/archives/class11-lab/no.jpg' alt='Sorry, No Image Available' />
<h2>". $new_row['item']."</h2><br>
<h4>Price:". $new_row['price']. " </h4>
<p>Description: ". $new_row['description'] ."</h4>
<p>Category: ". $new_row['category'] ."</p></div>";} } ?>
What I have here works perfectly fine, I just have no idea how to create headings to categorize the food types.
Thanks
回答1:
Initialize a category variable before you start fetching rows.
$category = null;
After you fetch each row, compare that row's category to the previous category. If it's different, output the header. Then that category becomes the new previous category.
while ($new_row = mysql_fetch_array($new_result)) {
if ($new_row['category'] != $category) {
echo "<h1>$new_row[category]</h1>";
$category = $new_row['category'];
}
// ... rest of your while loop contents ...
By the way, the mysql extension has been deprecated for quite a while and was removed in the current version of PHP. You should look into updating your code to use mysqli or PDO instead.
来源:https://stackoverflow.com/questions/43668497/create-category-headings-when-displaying-sql-data-using-php