Build Combobox with Item Selected

风格不统一 提交于 2019-12-25 04:27:06

问题


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 created before any quotes/apostrophes and is functioning properly.

$MCI = '';
$MCI = $row['MobileCarrierID'];

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

Thank you!


回答1:


You have

echo '
<select name="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...

<?php
echo '<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




回答2:


<?php 
$sql = mysqli_query("SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
?>
<select name="MobileCarrierName">
<?php
while ($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



来源:https://stackoverflow.com/questions/39071127/build-combobox-with-item-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!