Getting value from drop down menu in html and accessing it in php

How do I access the selected value of a drop down menu from html and get it in php? I've got a few fields like this:

    <html>";            
    $sql = "SELECT * FROM table";
    $stuff = mysql_query($sql) or die ("An error has occured.");
    while($row = mysql_fetch_array($stuff))
    {
        $body.= "<option>".$row['value']."</option>\n";
    }
    $body.="<html>

I want to take this value and use it to filter the results I get from another query. How would I go about doing this?

Answers


In your current file

You need to add form around your select element. I have also fix some of your code so that the select tags are included and the option tags actually have a value set in them!

I have also added in a submit button so you can actually send the form.

$body .= '<select name="filter">
       <form action="" method="post">';            
$sql = "SELECT * FROM table";
$stuff = mysql_query($sql) or die ("An error has occured.");
while($row = mysql_fetch_array($stuff))
{
    $value = htmlentities($row['value'], ENT_COMPAT, 'UTF-8');
    $body .= '<option value="' . $value . '">' . 
            "$value</option>\n";
}
$body .= '</select>
    <input type="submit" />
    </form>';
In results.php

You now need to grab the filter from the POST values and use it in your query to filter the results like so:

$filter = '';
if(isset($_POST['filter'])) {
    $filter = mysql_real_escape_string($_POST['filter']);
}
$SQL = "SELECT * FROM `table_name` WHERE `field` = '$filter'";
// you can do the rest of the code from here :)
All in one file:
<?php
if('POST' == $_SERVER['REQUEST_METHOD']) {
    $filter = '';
    if(isset($_POST['filter'])) {
        $filter = mysql_real_escape_string($_POST['filter']);
    }
    $SQL = "SELECT * FROM `table_name` WHERE `field` = '$filter'";
    // you can do the rest of the code from here :)
}

$body .= '<select name="filter">
       <form action="results.php" method="post">';            
$sql = "SELECT * FROM table";
$stuff = mysql_query($sql) or die ("An error has occured.");
while($row = mysql_fetch_array($stuff))
{
    $value = htmlentities($row['value'], ENT_COMPAT, 'UTF-8');
    $body .= '<option value="' . $value . '">' . 
            "$value</option>\n";
}
$body .= '</select>
    <input type="submit" />
    </form>';

Need Your Help

sending json object using $.ajax doesnt get to servlet

java jquery ajax json servlets

I'm trying to send json Object whit Ajax(POST) to my Servlet,

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.