Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Refine PHP query using dropdownbox



3:25 pm on May 26, 2014 (gmt 0)


I am just teaching myself PHP for some fun, and am a bit stuck.

I have a search query to search a suburb for businesses. This works fine. I would like to refine the search query with a dropdownbox for particular categories (fast food, public transport etc). In a perfect world I'd like that to be auto-populated from the database, but baby steps, right? Any help would be greatly appreciated!

HTML/PHP code is below:

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<table align="center" width="80%">
<tr align="center"><td>Search suburb:</td></tr><tr align="center"><td><input type=text value="" autofocus name="suburb"></td></tr><tr align="center"><td><input type="submit" value="Search" name="submit1"></td></tr>
<select size="1" name="dropdown">
<option value="" selected>Refine search:</option>
<option value="first">Burger</option>
<option value="last">Coffee</option>
<option value="company">Fast Food</option>
<option value="address">Health&Fitness</option>
<option value="town">Library</option>
<option value="city">Pizza</option>
<option value="postcode">Public Transport</option>


$link=mysql_connect($server, $username, $password) or die("Could not connect to database");

if($suburb!="" )
$query="select BusinessName, Address, Suburb FROM Business WHERE Suburb='$suburb'";
echo '<table border="1" cellspacing="18" width="50%" align="center" >';
echo "
<tr align='center'>
<tr align='center'>
<td>{$row[0]} </td>

<tr align='center'>
<tr align='center'>
<td>{$row[1]} </td>

<tr align='center'>
<tr align='center'>
<td>{$row[2]} </td>

echo "<tr><td>&nbsp</td></tr>";
echo "</table>";


6:34 am on May 31, 2014 (gmt 0)

something like that ...

$suburb = trim($_POST['suburb']);
if($suburb != "") {
$query = "select BusinessName, Address, Suburb FROM Business WHERE Suburb='$suburb'";

$dropdownValue = $_POST['dropdown'];
if (! empty($dropdownValue)) {
$query .= " AND category='".mysql_real_escape_string($dropdownValue)."'";

"category" is the fieldname in database, i dont know how you wanna name it, the name "dropdown" for a dropdown is not very good :) ... name it "category" in your html.

Important: You are building an sql-injection site here ... anyone can read or delete your whole database because you using variables from post without quoting in a sql string! you should do something like that ...

$query = "select BusinessName, Address, Suburb FROM Business WHERE Suburb='".mysql_real_escape_string($suburb)."'";

Featured Threads

Hot Threads This Week

Hot Threads This Month