G90DD
G90DD

Reputation: 129

How can I use the results of my query in a dropdown menu?

I am trying to create a dropdown menu that will have as options certain fields recovered from a database using a for loop.

I am doing the following:

for ($article_id=1; $article_id <=30; $article_id++) 
{
    $sqltitles = "SELECT title FROM articles WHERE article_id='$article_id'";
    $cursor = mysqli_query($db, $sqltitles) or die($sqltitles."<br/><br/>".mysql_error());
    $row = mysqli_fetch_row($cursor);
    $titles = $row[0];

    echo $titles;
    echo "</br>";
}

Which draws all the titles from the database and shows them one at a time.

Is there any way to make all those titles appear as options to a dropdown menu, so the user can select which one to read?

Upvotes: 0

Views: 28

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

Something like this should work. I made a modification to how the query is working. If you specify article IDs for a range of articles in your query rather than just one specific ID, you should be able to execute only one query instead of one for each ID you want to retrieve. Regardless of whether or not you decide to use the approach I suggested, the syntax for creating the dropdown menu should be the same.

<select>
<?php 
    $sqltitles = "SELECT title FROM articles WHERE article_id BETWEEN 1 AND 30" ;
    $cursor = mysqli_query($db, $sqltitles) or die($sqltitles."<br/><br/>".mysql_error());
    while ($row = mysqli_fetch_row($cursor)) {
        echo '<option value ="' . $row[0] . '">' . $row[0] . '</option>';
    }
?>
</select>

Here is a good reference for how to create HTML <select> tags.

Upvotes: 1

Scott S
Scott S

Reputation: 90

try something along the lines of...

echo '<select name="dropdownname">';

foreach ($titles as $key => $val) {
    echo('<option value="' . $val .'">' . $val . '</option>');
}

echo '</select>';

Upvotes: 0

Related Questions