Create Category Headings when displaying SQL data using PHP

前端 未结 1 481
粉色の甜心
粉色の甜心 2021-01-16 10:27

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.

相关标签:
1条回答
  • 2021-01-16 10:59

    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.

    0 讨论(0)
提交回复
热议问题