Web Hosting Talk







View Full Version : sending a form's results to a mysql database


Davey Gale
02-07-2005, 03:00 PM
Dear All

I am competent at setting up a php script that sends the results of a form to a mysql database. (this is using basic text fields).

I want to create a form that gives the user about 4 or 5 different questions and instead of a text box there is a drop down menu next to each question for them to pick a few different options.

e.g. Question: How old are you?
Answers: 0-18 / 19-30 / 31-45

Then when the visitor has answered all the questions they click submit and the results are delivered to the database.

Can anyone give me the basic script for this or point me to a tutorial, with one example question?

krumms
02-07-2005, 09:02 PM
I am competent at setting up a php script that sends the results of a form to a mysql database. (this is using basic text fields).

Then why do you need our help? The values selected by the user in the drop down combo box can be accessed in the same manner as you would access the data in a text field:


<form action="your_script.php" method="post">
<p>How old are you? <select name="age">
<option value="0">-- Select an Age </option>
<option value="1">0-18</option>
<option value="2">19-30</option>
<option value="3">31-45</option>
<option value="4">Really Old</option>
</select>
<input type="submit" value="Go" />
</form>


Then your_script.php:


<?php
$age = $_REQUEST['age'];
// basic, crappy form validation for the 'age' field.
if (isset ($age) && ($age > 0) && ($age <= 4)) {
// connect to the database (this is PEAR::DB - http://pear.php.net)
$conn =& DB::connect ('mysql://user:password@localhost/db');
if (DB::isError ($conn)) {
die ('Could not connect to the database.');
}

// place the form data into the database - DB::query automatically addslashes
// your scalar parameters
$query = 'INSERT INTO responses (age) VALUES (?)';
$conn->query ($query, array ($age));

// disconnect from the database
$conn->disconnect ();
}
else {
die ('Invalid age field!');
}
?>


Please be aware that although I've used a numeric value for all the options in the drop down list, it's possible to use string values too (i.e. I could have easily used the strings "0-18", "19-30", etc. - use whatever is more appropriate for your situation/source data)

Hope all that helps.