How to set the selected option <select>

I am trying to get my choice to show the selected category from my database in a dropdown. I can only show this when I hit the submit button.

<?php

    (isset($_POST["kategori"])) ? $kategori = $_POST["kategori"] : $kategori=1;
    $sql = "SELECT * FROM kategori" 
    $result = mysqli_query($db, $sql);
    while($produkt = mysqli_fetch_array($result)) {

?>

 <option <?php if ($kategori == $produkt['kategori_id'] ) echo 'selected'; ?> 
 value="<? echo $produkt['kategori_id']; ?>">
 <? echo $produkt['kategori_navn']; ?></option>

<?php
}
?>

      

Apparently I am getting the value from POST and so it shows the category first when I hit submit.

I need to make a selection from my database with the product ID of the product and use its ID to mark which category is installed.

And I can't figure out how to do it.

+3


source to share


3 answers


Try

$sql = "SELECT * FROM kategori" 
$result = mysqli_query($db, $sql);

while($produkt = mysqli_fetch_array($result)) {

     if ( $kategori == $produkt['kategori_id']  ) : ?>
        <option selected="selected" value="<?=$produkt['kategori_id']; ?>"><?=$produkt['kategori_navn']; ?></option>
     <?php else: ?>
        <option value="<?=$produkt['kategori_id']; ?>"><?=$produkt['kategori_navn']; ?></option>
     <?php endif; ?>

<?php } ?>

      



Where $kategori

is the variable that has the previously selected parameter value.

+2


source


Just try adding like this:



  <option <?php if ($kategori == $produkt['kategori_id'] ) ?> value="<? echo $produkt['kategori_id']; ?>" selected="selected"><? echo $produkt['kategori_navn']; ?></option>

      

0


source


Try the following query: $ sql = "select * from kategori

where kategori_id

IN ($ kategori)";

you will automatically get the corresponding category that you can select without using the while loop

-1


source







All Articles