Home > Mobile >  Dropdown list populated with blank entries (MYSQLI query)
Dropdown list populated with blank entries (MYSQLI query)

Time:08-05

I'm creating a dropdown select box with the bootstrap class "form-control". Idea is to choose categories for a blog post.

For the selection, I'm using a MYSQLI query to draw the names of the categories. However, my dropdown list is being populated with blank options between each actual value, from the database. Code is as follows:

     <?php

        echo '<select >';
        $query= "SELECT * FROM categories";
        $select_all_categories_queries=mysqli_query($connection,$query);

        while ($row = mysqli_fetch_assoc($select_all_categories_queries)) {
            $cat_title = $row['cat_title'];
            if (!empty($cat_title)){
            echo "<option>
                   {$cat_title}
                    <option>"; 
        }
           }
        echo '</select>';
        ?>

I've tried using an If statement to filter out 'empty' entries, even though my database has none. However it doesn't work.

P.S I'm using Bootstrap 3 (This site uses the working environment of an older course)

This is the HTML output:

<select >
<option>Business</option>
<option></option>
<option>World</option>
<option></option>
<option>Learning</option>
<option></option>
<option>Javascript</option>
<option></option>
<option> Bootstrap</option>
<option></option>
<option>Laravel</option>
<option></option>
</select>

This is the output from the query

    Array
(
    [cat_id] =&gt; 1
    [cat_title] =&gt; Business
)
Array
(
    [cat_id] =&gt; 2
    [cat_title] =&gt; World
)
Array
(
    [cat_id] =&gt; 3
    [cat_title] =&gt; Learning
)
Array
(
    [cat_id] =&gt; 4
    [cat_title] =&gt; Javascript
)
Array
(
    [cat_id] =&gt; 5
    [cat_title] =&gt; Bootstrap
)
Array
(
    [cat_id] =&gt; 6
    [cat_title] =&gt; Laravel
)

CodePudding user response:

The correct code is

     <?php

        echo '<select >';
        $query= "SELECT * FROM categories";
        $select_all_categories_queries=mysqli_query($connection,$query);

        while ($row = mysqli_fetch_assoc($select_all_categories_queries)) {
            $cat_title = $row['cat_title'];
            if (!empty($cat_title)){
            echo "<option>
                   {$cat_title}
                    </option>"; //  <--------
        }
           }
        echo '</select>';
        ?>

The second needs to be . Otherwise the browser thinks there are two option tags there.

  • Related