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] => 1
[cat_title] => Business
)
Array
(
[cat_id] => 2
[cat_title] => World
)
Array
(
[cat_id] => 3
[cat_title] => Learning
)
Array
(
[cat_id] => 4
[cat_title] => Javascript
)
Array
(
[cat_id] => 5
[cat_title] => Bootstrap
)
Array
(
[cat_id] => 6
[cat_title] => 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.