Kumaran Senapathy
Kumaran Senapathy

Reputation: 1283

Passing value from a dropdown list from one php to another

I have

  1. A dropdown list populated from a MySQL table.
  2. A button.
  3. Another php page

What I need to do:

  1. On clicking the button, pass the value selected from the dropdown list as a variable to second php page.

  2. Pass that variable into a mysql query on the second php page. eg: $result = mysql_query("Select * from table where name like "$drop_down_value");

I am new to php and pardon my naivety.

This is my code to get values for the dropdown list:

function dropdown_query()
{
mysql_connect("localhost","root","root") or die("Failed to connect with database!!!!");
mysql_select_db("student_test") or die("cannot select DB");
$result = mysql_query("Select * from marks");
if($result=== FALSE){
die(mysql_error());
}
while($r=mysql_fetch_array($result))
{
echo '<option value="' .$r['marks'] . '">' . $r['marks'] . '</option>';

}

and this is my HTML part:

select name="dropdown" onchange="somefunc()">
<option value="">Select...</option>
<?php dropdown_query()?>
</select>

Lets say I use a similar query on another php. But would use the value selected on this page as a variable in that query.

Upvotes: 0

Views: 8524

Answers (4)

Avinash Kumar
Avinash Kumar

Reputation: 43

The answer to your question is to use the $_POST or $_GET superglobal variables in PHP. You can use either of these to obtain the value of the dropdown list from the first page after the button is clicked. For example, you could use the following code to obtain the value of the dropdown list:

$drop_down_value = $_POST['dropdown'];

Then, you can pass this variable into your MySQL query on the second page, as you have outlined in your question:

$result = mysql_query("Select * from table where name like "$drop_down_value");

Upvotes: 0

chien pin wang
chien pin wang

Reputation: 567

you will need javascript to do this. The page already finish loading. php script wont work after page finish loading. try jquery, ez to use

Upvotes: 0

H&#229;kan
H&#229;kan

Reputation: 186

Your page1 will have a form something like

<form action="page2.php" method="post">
 <p>Name: <input type="text" name="name" /></p>
 <p><input type="submit" /></p>
</form>

And in page2.php you can do something along the lines of

$name = $_POST['name'];
$sql  = "SELECT * FROM table WHERE name LIKE '$name'";
...

(But make sure to scrub the user input before using it on page2.php!)

Upvotes: 0

Tomanow
Tomanow

Reputation: 7377

By wrapping the drop down in a form with POST method, you can send the value to the next page and retrieve via $_POST['your_field_name']. See the docs.

Upvotes: 0

Related Questions