I'm trying to show a specific item in the row when an item in the dropdown list is selected.
To clarify, lets say I have item1 chosen in the dropdown menu, and when item1 is chosen, I want price for item1 shown in another field on the page.
ps. I'm trying to make an inventory and ordering form which is connected to an MYSQL database.
Thanks in advance.
Here is my PHP code.
function dropdown( $alcohol, array $options, $selected=null )
{
/*** begin the select ***/
$dropdown = ''."\n";
$selected = $selected;
/*** loop over the options ***/
foreach( $options as $key=>$option )
{
/*** assign a selected value ***/
$select = $selected==$key ? ' selected' : null;
/*** add each option to the dropdown ***/
$dropdown .= '
`value="'.$key.'"'.$select.'>'.$option.'
'."\n";}
/*** close the select ***/
$dropdown .= ''."\n";
/*** and return the completed dropdown ***/
return $dropdown;
}
?>
mysql_connect('localhost', 'root', '');
mysql_select_db('');
$sql = "SELECT alcohol FROM alcohol ";
$result = mysql_query($sql);
echo "";
while ($row = mysql_fetch_array($result)) {
echo "" . $row['alcohol'] . "";
}
echo "";
?>
//NEW STUFF BELOW THIS//
--- Select Alcohol ---
mysql_connect('localhost', 'root', '');
mysql_select_db('');
$sql = "SELECT alcohol FROM alcohol";
$result1 = mysql_query($sql);
while ($row = mysql_fetch_array($result1)) {
echo "" . $row['alcohol'] . "";
}
$dropdown1 = empty($_POST['alcohol'])? die ("ERROR: Select from dropdown") : mysql_escape_string($_POST['alcohol']);
echo "";
?>
if(isset($_POST['Submit'])) {
mysql_connect('localhost', 'root', '');
mysql_select_db('');
$sql = "SElECT * FROM alcohol where '$dropdown1' = alcohol";
$result = mysql_query($sql) or die(mysql_error());
?>
while ($row = mysql_fetch_array($result)) {
echo "
".$row['alcohol']."".$row['price']."".$row['quantity_in_stock']."";}
}
?>
解决方案
First of all, use mysqli. Mysql_* is deprecated and will be removed in a future version.
Now that we have that out of the way, I would add a "marker" character in the original dropdown select values in order to get the value. Pick a Unicode character that wouldn't normally be in your database, and echo that in the value so it looks like this:
$name
Then in the code above, split the value at the @ character and pick out what is after it in order to get the secondary value. That should save you a database operation in the long run.
Good luck!