I am having a problem with updating some values in my database. When I want to change a value using a drop down box, it automatically puts in the first value in the dropdown menu. What I want is to get the value that is already set in the database.
Here is my code:
<select name="vrijwilligerID">
<?php
$vrijwilligerID = $_POST["vrijwilligerID"];
$query = "SELECT voornaam, achternaam, vrijwilligerID FROM vrijwilliger;";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)){
echo "<option value=".$row['vrijwilligerID'].">".$row["voornaam"]." ".$row["achternaam"]."</option>";
}
?>
</select>
Does anyone know how to get this right? Thank you in advance.
Based on the selected item you have to add selected attribute to the option.
try this
<select name="vrijwilligerID">
<?php
$vrijwilligerID = $_POST["vrijwilligerID"];
$query =" SELECT voornaam, achternaam, vrijwilligerID
FROM vrijwilliger;";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)){
if($row["vrijwilligerID"]==$vrijwilligerID)
echo "<option value=".$row['vrijwilligerID']." selected>".$row["voornaam"]." ".$row["achternaam"]."</option>";
else
echo "<option value=".$row['vrijwilligerID'].">".$row["voornaam"]." ".$row["achternaam"]."</option>";
}
?>
</select>
Its easy enough to resolve that using php, but using mysqls IF() function you can have the selected option directly. Using mysqls concat() you could get your desired result as well.
(ofcourse we're not using any postsvars in our scripts unsanitized are we ;) )
$iVrijwilligerid = filter_input(INPUT_POST, 'vrijwilligerID', FILTER_VALIDATE_INT, array("options"=> array("min_range"=>0, "max_range"=>999))) ;
if($iVrijwilligerid)
{
$sQry = <<<QRY
SELECT
CONCAT('<option value="', vrijwilligerID, '"',IF((SELECT vrijwilligerID FROM vrijwilliger WHERE vrijwilligerID=$iVrijwilligerid), ' selected="selected"', '' ),'>',voornaam, ,achternaam,'</option>') AS optItem
FROM
vrijwilliger
WHERE
your clause here
QRY;
$oResult = mysql_query( $sQry );
while($aRow=mysql_fetch_assoc( $oResult ))
{
echo $aRow['optItem'];
}
}
else
{
// nada
}