I can't figure out why my drop down list, which is populated from Mysql, is giving me a number instead of the string value. Below is the code for the drop down list, which properly displays the item names. The problem is when I pull the selected item later I get a number instead of the string item name the user selected.
<select name="product1" class="form-control" id="sel1">
<?php
require('./PHPConnect.php');
$dropdown = array();
$downquery = "SELECT * FROM masterDESC";
$response = @mysqli_query($dbc, $downquery);
if($response){
while(($row = @mysqli_fetch_array($response,MYSQL_ASSOC))){
$dropdown[] = $row['DESCRIPTION'];
}
}
foreach($dropdown as $key => $value){
echo '<option value=' . $key . '>' . $value . '</option>';
}
echo "</select>";
mysqli_close($dbc);
?>
Here is the code later used to pull the selected item.
$product1 = $_POST['product1'];
Any thoughts?
Never mind I got it figured out. It was the key value pair on the foreach. It was necessary for a similar drop down I created in the past but didn't work here. I just got rid of the foreach and it worked.
<select name="product1" class="form-control" id="sel1">
<?php
require('./PHPConnect.php');
//$dropdown = array();
$downquery = "SELECT *
FROM masterDESC";
$response = @mysqli_query($dbc, $downquery);
if($response){
while(($row = @mysqli_fetch_array($response,MYSQL_ASSOC))){
$dropdown = "<option value=\"{$row['DESCRIPTION']}\">
{$row['DESCRIPTION']}</option>
";
echo $dropdown;
}
}
echo "</select>";
mysqli_close($dbc);
?>
It is spitting put the index number because you are retrieving an array which is just the description values (from this "$dropdown[] = $row['DESCRIPTION'];" you have returned from the DB and when there are no keys listed - the array index is the $key - therefore the number
you need to change the following
foreach($dropdown as $key => $value){
echo '<option value=' . $key . '>' . $value . '</option>';
}
to this and set the value of the option to the same as the displayed content (or leave it with the number and reference it later as $dropdown[index].
foreach($dropdown as $value){
echo '<option value="' . $value. '">' . $value . '</option>';
}