Reputation: 85
I'm trying to get my select option to show the selected category from my DB in the dropdown. I can only get it to show it, when i hit my 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’m getting the value from POST, and that’s why it first shows the category when I hit submit.
I need to make a select from my database with the product ID of the product, and use it’s id to mark which category is set.
And I can’t figure out how to do that.
Upvotes: 3
Views: 655
Reputation: 285
Try the query like this:
$sql="select * from kategori
where kategori_id
IN ($kategori)";
you will automatically get the matched category which you can select it without using while loop
Upvotes: -1
Reputation: 420
Just try to add like this:
<option <?php if ($kategori == $produkt['kategori_id'] ) ?> value="<? echo $produkt['kategori_id']; ?>" selected="selected"><? echo $produkt['kategori_navn']; ?></option>
Upvotes: 0
Reputation: 898
Try it
$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 variable which has the previously selected option value.
Upvotes: 2