user1344705
user1344705

Reputation: 91

Display data from SQL according to search options

I am trying to make a search form that will help users filter their results from the database.

How do you sort the results according to the option chosen from the dropdown list?

I mean sort like, if the user selects "Name" from the list, when they hit submit, the table will display all the data but the names will be ordered either ascending or descending (also a user option)

form (sample of drop down list and radio buttons):

<select name="sort">
    <option value="x">Select a field</option>
    <option value="1">Name</option>
    <option value="2">City</option>
    <option value="3">Occupation</option>
</select>
&nbsp;
ascending<input type="radio" name="sort_order" value="asc">
&nbsp;
descending<input type="radio" name="sort_order" value="desc">

query:

if ($sort !== "x")
$SQL="SELECT * FROM data //what do I add here?//

What is the most efficient way of accomplishing this? Any help is appreciated!
Feel free to ask if I'm not being clear as I'm not sure how to word my question well.

EDIT:

I am using an array $value() to display the data on a table.

Sample display:

for ($i=0;$i<$num_results;$i++)
        {
        $row=mysql_fetch_array($result);
        echo "<tr>";
        echo "<td>".$row["Name"]."</td>";
        if (in_array("City",$value))
        echo "<td>".$row["City"]."</td>";
           if (in_array("Occupation",$value))
           echo "<td>".$row["Occupation"]."</td>";

How do I save the results for my $sort and $sort_order into $value() ?

Upvotes: 2

Views: 632

Answers (2)

user1432124
user1432124

Reputation:

mysql_query("select * from data order by ".mysql_real_escape_string($_POST['sort'])." ".mysql_real_escape_string($_POST['sort_order']));

Write your sql query like this

Upvotes: 1

John Conde
John Conde

Reputation: 219884

$sort = mysql_real_escape_string($_POST['sort']);
$sort_order = mysql_real_escape_string($_POST['sort_order']);
$SQL="SELECT * FROM data ORDER BY $sort $sort_order";

Upvotes: 0

Related Questions