PDA

View Full Version : Insert Dropdown list data into MySQL



inplaytoday
13 Apr 2011, 05:51 PM
Hi, I'm unable to find any info for this on Google.

I know how to use php and an html form to write text data to a database, but how can this be done with a pre-populated (using database) Select Dropdown List.

I need a registered user to be able to:

1. Select A Value from displayed Dropdown List.
2. Use PHP to send that selection to a different Table in my database (MySQL).

There are plenty of tutorials on the net about how to populate dropdown lists, but none that tell how to 'grab' a selected value and record it into a database.


Here is the code I've used so far:
Code:

<html>
<body>

<form method="post" action="update.php">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

<input type="submit" value="Submit Pick" />

</body>
</html>

Using update.php that looks like this:
Code:

<?php
$Car = $_POST['cars']

mysql_connect ('localhost', 'username', 'password') or die ('Error: ' .mysql_error());
mysql_select_db ("data_base");

$query="INSERT INTO user (FirstName)VALUE ('".$Car."')";
mysql_query($query) or die ('Error submitting');

echo "You Chose: " .$Car ;

?>

resdog
14 Apr 2011, 11:57 AM
How is your table structured? From here, it looks like you are trying to insert the value of $Car into a new row, but only in the FirstName column. Do you get the 'Error submitting' message? What happens when you run this?

First, close the form with a </form> tag. Other than that, everything goes smoothly, as the variable $Car is being assigned correctly. I don't think the word "VALUE" is correct. It should be VALUES, even though you only have one value to put in. Try that and see if it works. Also, I'd add a space after (FirstName) before VALUES.