Flamin_Squirrel
Flamin_Squirrel

Reputation: 31

Return dropdown selection - php/sql

I'm populating a drop down box using values from sql, but I'm having trouble getting the drop down to return a value. After much searching, I've come across many ideas but none have worked. Any help is appreciated.

The relevant code I have is shown below. Please be gentle, this is fairly new to me!

Thanks.

<?php

echo "<form action=\"theForm\" method=\"GET\">";
echo "<select name=\"courier_select\">";

$query = mysql_query("SELECT DISTINCT(courier) AS courier FROM reviews ORDER BY courier ASC");
while($row = mysql_fetch_array($query)){ echo "<option value=\"courier\">" . $row['courier'] . "</option>"; }

echo "</select>";
echo "</form>";

echo $_GET['theForm'];

?>

Upvotes: 0

Views: 631

Answers (1)

BenM
BenM

Reputation: 53198

Because you're explicitly setting the value attribute of <option> element to courier, the value of courier_select will always be that.

You need to set the value to be that pulled from the database, as follows:

while( $row = mysql_fetch_array($query) )
{ 
    echo '<option value="'.$row['courier'].'">'.$row['courier'].'</option>'; 
}

Now, when you try to access the <select> element's value (using either $_GET['courier_select'] or $_POST['courier_select'] depending upon the form's method), you'll get the selected value.

It's worth noting that the mysql_* family of functions is now deprecated, and you should investigate the use of either MySQLi or PDO before putting this code into production.


Also, it appears that you lack a basic grasp of how <form> elements work. The form needs to be submitted, and the action attribute defines where the submitted data should be sent. You will need to update the action attribute to be a page on your website that handles the form. Alternatively, remove the attribute to have the form submit to the page it resides on.

Once the form has been submitted (you'll need a <button type="submit">Submit</button> for that), you can then access the form's data using the $_GET superglobal (because you're specifying a method of GET), or $_POST if you used the POST method.

Both $_GET and $_POST are arrays, and their keys refer to the form elements' names. So in order to get the value of the courier_select selectbox, you can use:

$_GET['courier_select'];

Upvotes: 1

Related Questions