Attempting to output "</ul>" specifically for particular elements within an array

I am currently working on a project where I need to display category names and list any post that belongs to that category in a bootstrap list group. The issue I am facing is how to properly echo the closing <ul> tag at the end of each category so that a new list can begin. If you have any ideas or suggestions on how to improve this, please let me know. My goal is to organize each category in its own collapsible list panel for better presentation. You can find more information about Bootstrap collapse panels here.

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
</ul>  

Here is the code I have attempted so far:

<?php

   $query = "SELECT post_category,post_title
               FROM posts 
           ORDER BY post_category";
   $select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
    <div class="col-lg-12">
        <ul class="list-group">
        <?php
             $title = "";
             while ($row = mysqli_fetch_array($select_categories_sidebars)) {
                 if ($row['post_category'] != $title) {
                      echo '<ul><li class="list-group-item">'.$row['post_category'].'</li><br>';
                      $title = $row['post_category'];
                 }
                 echo '<li class="list-group-item">'.$row['post_title']</li>;
             }
?>

Answer №1

It seems like there may be an issue with missing closing </ul> tag in the code provided.

Here is a revised version:

<?php
$query = "SELECT post_category,post_title
            FROM posts 
        ORDER BY post_category";
$select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
 <div class="col-lg-12">
    <ul class="list-group">
    <?php
         $title = "";
         $someItem=false;
         while ($row = mysqli_fetch_array($select_categories_sidebars)) {
             if ($row['post_category'] != $title) {
                  if ($someItem)
                  {
                      echo '</ul>';
                  }
                  $someItem=true;
                  echo '<ul><li class="list-group-item">'.$row['post_category'].'</li><br>';
                  $title = $row['post_category'];
             }
             echo '<li class="list-group-item">'.$row['post_title']</li>;
         }
 ?>
 </ul>
 </div>
 </div>

Answer №2

You should always include a closing </ul> tag at the end of each list, as shown in the example below. Your code needs to be modified so that each list starts with an opening <ul> tag and ends with a closing </ul> tag. Additionally, each list item should start with an opening <li> tag and end with a closing </li> tag. It is recommended to make separate queries for each category.

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
</ul>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
</ul>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
</ul>  

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

having difficulty understanding how to incorporate a layout update in my recently developed module

Help needed to integrate a custom script on the success page. I have created a file called luisvalenciaaffiliatecj.xml with the following path: /app/design/frontend/base/default/layout/luisvalenciaaffiliatecj.xml <?xml version="1.0"?> <layout ve ...

"Retrieve the values of the items that have been chosen from a list using jQuery

In my PHP page, I have a list displayed using the following script: <div id='demo' style="padding-left:20px"> <select name='lists[]' multiple='multiple' class='multiselect' > <?php $sql="select list ...

Exploring and sifting through JSON data in PHP

Can someone assist me with parsing and navigating through JSON results using PHP? In the example below, I need to specifically target technology categories. What I want to achieve is to identify if the category 'analytics' exists in the result, ...

What is the best way to send information from a main blade to an included modal?

Trying to implement a functionality where a modal is triggered on clicking a button and an array named $incident is passed through to the properties of a Vue component. What is the correct way to pass data from a parent blade to an included modal? I initia ...

Obtain the Foursquare access_token through a PHP cURL request

I'm currently testing a cURL function to retrieve the access token for a specific user on Foursquare. The given function displays the access token in JSON format. {"access_token":"5B25GW5LF3L4W04PALHK32X5Z3YGNUUVDHM2TFBQOWZSQ121"} However, I am enco ...

Tips for embedding Javascript code within the window.write() function

I have a JavaScript function that opens a new window to display an image specified in the data variable. I want the new window to close when the user clicks anywhere on it. I've tried inserting some JavaScript code within window.write() but it doesn&a ...

Successful query execution is achieved in phpMyAdmin but fails when attempted in PHP

Is there a reason why a query in PHP may not return the same data as it does in phpMyAdmin SQL? $query = "UPDATE `boards` SET `contestPlaces`=0, `contestPlacesFilled`=0"; $result = mysql_query($query) or die("ERROR:QUERY_FAILED timeset 8" . mysql_error( ...

Is there a way for me to retrieve a PHP variable and populate form fields with it?

In this PHP code snippet, the goal is to display a PHP variable in the value attribute of a form field textbox. <?php while($result=mysql_fetch_array($query)) { $title=$result["title"]; $date=$result["date"]; $body=$result["body ...

Attempting to change the names of two files using PHP

Running Ubuntu 12.04 with apache2 + nginx (ISPManager) Wowza Media Server is saving my recorded .flv videos to {root-of-the-server}/movies The video file name is obtained from $_GET['rfile'] using: $this->request->get('rfile'). ...

Traversing a multi-dimensional array with changing keys in PHP

Recently delving back into the world of basic PHP, I encountered a roadblock while dealing with a JSON response. I successfully converted the response into an Array, but it seems to be multi-dimensional. The challenge lies in isolating and extracting value ...

Display 1 row of content on larger LG screens and 2 rows on medium-sized MD screens using Bootstrap

How can I achieve 1 row with 12 cells on a large screen in Bootstrap, and for a smaller screen have 2 rows with 6 cells? Here is a visual representation of what I am trying to accomplish: https://i.stack.imgur.com/NgfaP.png This is the code I attempted: ...

Laravel responses with 404 for POST requests

Currently, I am in the process of creating a signup API that involves making two different API calls: first a GET call and then a POST call. When conducting the GET [POSTMAN] call, the response from the controller is correct but upon making the POST call, ...

Enable drawing on a div element and synchronizing it across multiple divs using Javascript and HTML5

I am embarking on a project to create a website that allows users to doodle on an element and share it with others viewing the page using ajax - essentially a small-scale whiteboard feature. While I have a good grasp of HTML, CSS, Javascript (specificall ...

Why does the appearance of my PHP spreadsheet change when I attempt to print it?

After using a CSS stylesheet to position my textboxes correctly, I noticed that in Chrome everything appeared fine. However, when attempting to print the site (Ctrl+P), each sentence and textbox shifted. How can I ensure they remain in place? <!-- #cap ...

Fetch and showcase JSON information from a CodeIgniter method

Is there a way to retrieve data from a SQL database using ajax (json) with Codeigniter or PHP? I have attempted it, but the result shows up as "undefined." Here is the code snippet: My jQuery code snippet: $('[id^="menuitem_"]').on('click& ...

A group of Symfony Messenger consumers working together efficiently

Is it feasible to have a shared pool of messenger consumers for the same queue? I attempted to utilize the Redis consumer= options, but to no avail. Perhaps a "pool" middleware could facilitate routing to particular transports? ...

Inspecting Facebook links

Currently working on a website and interested in incorporating a feature similar to what Facebook has. I'm referring to the link inspector, but I'm not entirely sure if that's its official name. Allow me to provide an example to clarify my r ...

Traverse HTML table elements using a PHP loop after submitting a form

I have a jQuery function that dynamically adds rows with input fields to a form. Each cell in the table gets text boxes with distinct names. Here is an example of the HTML generated: <table width="400" border="0" cellspacing="0" cellpadding="2px" marg ...

Determine in PHP if a decimal number is greater than 0.3

Trying to find out if a number has a decimal using the following code snippet. Example: $val = 3.3; if (is_numeric( $val ) && floor( $val ) != $val) { return true; } Is there a way to determine if the decimal value of the number is equal to o ...

Using jQuery to send a GET request to the current page with specified parameters

Within my application, hosted on a PHP page, I am aiming to trigger a GET request upon selecting an option from a dropdown menu. The URL of the page is: www.mydomain.it/admin/gest-prenotazioni-piazzola.php I intend to utilize jQuery to execute this GET r ...