Make an SQL query a drop down menu

2019-09-20 09:30发布

问题:

I have two SQL queries that display different results from my database. I'm using these results as navigation links in my nav bar. At the moment all the results display as a single line of text, I want to make each SQL query display as a drop down menu, with all the results from the query as an option in the drop down.

Here's the code I'm using:

<?php

$q = "SELECT cat_id, cat_name FROM Category";
$result = mysqli_query($_SESSION['conn'], $q);
while ($row = mysqli_fetch_row($result)) {
    echo "<a href='category.php?id=$row[0]'>$row[1]</a> ";
    //display product categories
}
mysqli_free_result($result); //free result

$q = "SELECT brand_id, brand_name FROM Brand";
$result = mysqli_query($_SESSION['conn'], $q);
while ($row = mysqli_fetch_row($result)) {
    echo "<a href='brand.php?id=$row[0]'>$row[1]</a> ";
    //display product Brands
}
?>

回答1:

use select option

echo "<select name='category'>";
while ($row = mysqli_fetch_row($result)){
   echo "<option value='$row[0]'>$row[1]</option> ";
}
echo "</select>";


回答2:

$q="SELECT cat_id, cat_name FROM Category";
$result = mysqli_query($_SESSION['conn'],$q);
$option1.="<select name='category'>";
while ($row = mysqli_fetch_row($result)){
   $option1.="<option value='$row[0]'>$row[1]</option> ";
}
$option1.="</select>"; 

same for second print this $option1 value in your view file



回答3:

<select onchange="document.location.href='category.php?id='+this.value;">  
<?php   
    $result = mysqli_query($_SESSION['conn'],$q);
    while ($row = mysqli_fetch_row($result)):?>
    <option value="<?=$row[0];?>"><?=$row[1];?></option>
    <?php endwhile;?>
</select>