Skip to content Skip to sidebar Skip to footer

Build Combobox With Item Selected

Trying to create a combo box with the user's current value selected. I'm thinking my issue is with the apostrophe's and quotes - can anyone with a sharp eye help? Variable $MCI is

Solution 1:

You have

echo '
<selectname="MobileCarrierName"><?php$sql=

which needs to be changed to

echo'<select name="MobileCarrierName">';
$sql= 

Also

$MCISelected = (' . $MCI . '==$row["MobileCarrierID"] ? " selected" : "");

needs to be changed to

$MCISelected = ($MCI==$row["MobileCarrierID"])? " selected" : "";

And your mysqli_query is missing the database connection ie

mysqli_query($db,$query);

Finally, close off with

echo'</select>';

Your quotes and brackets are off and you've placed your selected variable inside your value in the option, a complete edited code should look something like...

<?phpecho'<select name="MobileCarrierName">';
$sql = mysqli_query($conn, "SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
while ($row = mysqli_fetch_array($sql)){
$MCISelected = ($MCI==$row["MobileCarrierID"])? " selected" : "";
echo'<option '.$MCIselected.' value="'.$row["MobileCarrierID"].'">'.$row["MobileCarrierName"].'</option>';
}
echo'</select>';

Check out How to set an option from multiple options or array with different values to views as selected in select box using PHP for a guide on how it works

Solution 2:

<?php$sql = mysqli_query("SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
?><selectname="MobileCarrierName"><?phpwhile ($row = mysqli_fetch_array($sql)){
    $MCI = $row['MobileCarrierID'];
    $MCISelected = ($MCI==$row["MobileCarrierID"]) ? " selected" : "";
    echo"<option value=".$MCI." ".$MCISelected.">".$row['MobileCarrierName']."</option>";
}
?></select>

try this one

Post a Comment for "Build Combobox With Item Selected"