Page 1 of 1

Form with drop down list from query

Posted: Thu Feb 25, 2010 6:47 am
by dave.hawksworth
I am trying to design an input form based on a drop down list which uses an sql query as its source.
The following Query staement produces a drop down list but so far I have been unable to incorporate POST and Submit statements to allow me to pass the selected variable .
Code so far :-

<?
$username="uname";
$password="pwd";
$database="my_db";

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");


$result = mysql_query('SELECT * FROM `daysofweek`') or die(mysql_error());


echo '<select name="Day">';


while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['1'].'">'.$row['Day'].'</a>';
}


echo '</select>';


?>

Can anyone suggest the appropriate structure to create the form.
Thanks
Dave

Re: Form with drop down list from query

Posted: Thu Feb 25, 2010 7:15 am
by N1gel
You need to put your select in a form for it to be posted to another page. (I have made a tweak to your option as well as it was the incorrect closing tag)

Code: Select all

echo '<form method="post" action="destination.php">';
echo '<select name="Day">';
while ($row = mysql_fetch_assoc($result)) 
{
echo '<option value="'.$row['1'].'">'.$row['Day'].'</option>';
}
echo '</select>';
echo '<p><input type="submit" value="Query">';
echo '</form>';
You will need to change destination.php to the php file the page that you want to post this data to. You can then access the posted data as below

Code: Select all

echo $_POST['Day'];
If you are having trouble accessing the post data it is sometimes helpful to print everything that has been posted to the screen

Code: Select all

print_r($_POST);

Re: Form with drop down list from query

Posted: Thu Feb 25, 2010 10:17 am
by dave.hawksworth
Thanks for the quick response.
I have used your code and everthing appears to work smoothly except that the posted string is a blank.
( I confirmed this with a print command in the target script as you recomended.
Can you see why the posted variable is blank.
Thanks
Dave
The code now reads:-
<?
$username="user";
$password="pwd";
$database="my_db";

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");


$result = mysql_query('SELECT * FROM `daysofweek`') or die(mysql_error());
echo '<form method="post" action="array_script.php">';
echo '<select name="Day">';
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="'.$row['1'].'">'.$row['Day'].'</option>';
}
echo '</select>';
echo '<p><input type="submit" value="submit">';
echo '</form>';

?>