0

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!

Jake
  • 893
  • 2
  • 9
  • 17

2 Answers2

0
<?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

Mouner Mostafa
  • 132
  • 4
  • 18
0

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

Community
  • 1
  • 1
independent.guru
  • 580
  • 5
  • 18