PHP/MYSQL advanced search script. How? - php

I need some guidance to make an advanced search script for a website I'm working on.
I already know how to search the database for simple queries. The problem I'm encountering right now is how to search, when using multiple select boxes. For example:
This is just a simple form with different search options. The question is:
The visitor can choose to search on a country or city, both or even with all three options.
How do I catch that in the PHP script? Do I have to check if for example a city has been chosen, and fire a query based on that? But if I do that I would have to make different queries based on each select option.
In pseudo-code it would be something like this: (I imagine)
if country and city and something else is not null, launch a query to search in all three tables in the database.
But what to do when just the country has been chosen? Or just the city?
Is there a simple way to accomplish this?
Thanks in advance.

I like using an array to join conditions so I don't have to worry about leading or trailing AND's.
$conditions = array();
if ($formCondition1) {
$conditions[] = 'state = "'.$somevalue.'"';
}
if ($formCondition2) {
$conditions[] = 'country = "'.$somevalue.'"';
}
...
if ($formConditionN) {
$conditions[] = 'N = "'.$somevalue.'"';
}
//finally join the conditions together, the simplest case is with ANDs (if you need to add ORs, which it sounds like you don't, then this code would be a bit more complex)
$sqlStatement = 'SELECT field1, field2 FROM tableABC WHERE '.implode(' AND ', $conditions);
EDIT: don't forget to escape the input to prevent injection attacks, and of course test to make sure there are at least 1 condition before running the query.
EDIT: lol jswolf and I think very much alike :)

I make a $where array, add my conditions to it as necessary, and then implode it with ' AND ' as the glue. So something like:
$where = array();
if $city is defined
$where[] = "city = '".mysql_real_escape_string($city)."'";
fi
if $country is defined
$where[] = "country = '".mysql_real_escape_string($country)."'";
fi
...
if(count($where)) {
$query.= ' WHERE '.implode(' AND ', $where);
}

I would try something like:
$qry = "SELECT * FROM table WHERE ";
if ($country != '') {
$qry .= "country='".mysql_real_escape_string($country)."' AND "
}
if ($city != '') {
$qry .= "city='".mysql_real_escape_string($city)."' AND "
}
$qry .= '1';
$res = mysql_query($qry);
The query is built up depending on what is set. Note the "1" on the end of the query string which is always true. This is needed to follow the "WHERE" if $country and $city are both empty, or to follow the last "AND" if they are not.

Related

How to run MySQLi query dynamically

Is there any way to run mysqli query dynamically ? I am working on a small project who has dynamic form generation option. And then they want to filer those forms. Obviously we dont know how much will be form fields and how many filters they want. So is there any such way through which I can perform this action? Suppose if i can do something
SELECT * FROM table WHERE fld1 = 1 OR fld2 = 2 OR fld3 = 3....
Where those 1, 2, 3,... Can be something or maybe its empty depend on filters.
You can dynamically build your query in php by examining your $_POST values and then building out your where statement. Here's some pseudo code
foreach($_POST as $name=>$value)
{
$where[] = "`$key` = '$value'";
}
$sql = "SELECT * FROM table WHERE ".implode("OR", $where);
Of course you will need to either sanitize or use a prepared statement to make sure this is safe.
The best way to run it dynamically is by using PDO and classes, if youre confused about any of those two things check out the PHPGuru Jeffery Way found here: https://laracasts.com/series/php-for-beginners and check out his PHP tutorials, youll quickly learn what you need to do to be able to make a class that allows you to dynamically connect to your database!
Maybe do something like:
$Where = array();
foreach($_POST['form-field'] as $Field=>$Value){
if($Value){
$Where[] = $Field."=".$Value;
}
}
$Query = "SELECT * FROM table WHERE ".implode(" OR ",$Where);
You can use IN clause of in MySQL query.
Similar like this.
SELECT * FROM table
WHERE fld1 IN (1, 2, 3);
Hope this will help you.
$filter = '';
$filter .= 'fld1 = 1 OR ';
$filter .= 'fld2 = 2 OR ';
$filter .= 'fld3 = 3 OR ';
...
...
if(!empty($filter)) {
$filter = substr($filter,0,-2); // delete last OR
}
$query = "SELECT * FROM table WHERE ".$filter."";
...
Something like this would work, you have to modify the way you populate $filter
Hope this'll help.

Filters not working (Executing different PHP queries based on parameters)

I am trying to implement filters which will help users refine there search for other users. Here is an image of my search parameters just to provide you with a graphical representation of what I will soon convey:
There are three filters:
Gender
Age
Similarity in studies
By default, I want to convey all users on the system. So when a user goes onto users.php, every single user will be displayed, then, when the filters are applied, refine the results accordingly.
Not all three parameters have to be completed to start the search, for example, a user can simply search a female user and it should display all female users on search click.
I have tried to implement different queries for each scenario, but all users are always being displayed. If I specify I want to search for a female and then click search, it will do nothing, still showing me all users.
Also, I am struggling with the similarity in studies parameter. The way this works is that in a table called user_bio I am storing data regarding what the user is studying, the user can choose to not provide this information, so studying can also be empty in my table.
The way I want it to work is to look at what the logged in user is studying, and then find words which match in other peoples bio's. For example, I am currently logged in as Conor, and Conor is studying Computer Science. Ideally, an algorithm will run which searches other users bio from the user_bio table, and return all the users who have computer or science in their bio's. Im pretty sure this concerns the LIKE clause but I have never used it before so I cannot be certain.
Here is my current approach:
// processing filters
$refined_gender = htmlentities (strip_tags(#$_POST['gender']));
$age_from = htmlentities (strip_tags(#$_POST['age_from']));
$age_to = htmlentities (strip_tags(#$_POST['age_to']));
$studying = htmlentities (strip_tags(#$_POST['studying']));
$get_all_users = mysqli_query ($connect, "SELECT * FROM users" );
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (isset($_POST['submit'])){
// if gender parameter is used ...
if ($refined_gender){
$gender_statement = mysqli_prepare ($connect, "SELECT * FROM users WHERE gender = ?");
mysqli_stmt_bind_param($gender_statement, "s", $refined_gender);
mysqli_stmt_execute ($gender_statement);
mysqli_stmt_close($gender_statement);
}
// if studying parameter used...
if ($studying) {
// see explanation below...
}
// if gender and age parameter used...
if ($refined_gender && $age_from && $age_to){
$gen_and_age_statement = mysqli_prepare ($connect, "SELECT * FROM users WHERE gender = ? AND age BETWEEN ? AND ?");
mysqli_stmt_bind_param($gen_and_age_statement, "sss", $refined_gender, $age_from, $age_to);
mysqli_stmt_execute ($gen_and_age_statement);
mysqli_stmt_close($gen_and_age_statement);
}
}
Summary, what I need:
The SELECT * FROM users query to be executed by default on users.php. This will show all the users in the system.
For any filter to be applied. Not all filters need to be applied to get a result, a user can search for a female and click search, loading all female users in the system.
I need the query to change based on what filters have been applied. So if a user has searched for a male user, and the other two options are not selected, then query will be "SELECT * FROM users WHERE gender = '$var_here'.
Here iam providing code such that how can you write multiple filter option inside a single query..but here i didn't mention about your 3rd filter option studing,because its about another table and you were not mentioned it clearly such that it's linked to this table using foreign keys or following relational database structure.any way multi filter option is as follows..here i added database connect and escape injection's functions...if u don't need that neglect that part..
function escape($e_string)
{
global $connect;
if(!isset($connect))
{
// DATABASE CONNECTION QUERY
$connect = mysqli_connect("servername", "username", "password", "");
if (!$connect)
die("Connection failed: " . mysqli_connect_error());
}
$e_string = trim(utf8_encode($e_string));
$e_string = mysqli_real_escape_string($connect,$e_string);
return $e_string;
}
// processing filters
$refined_gender = isset($_POST['gender']) ? escape($_POST['gender']) : '';
$age_from = isset($_POST['age_from']) ? escape($_POST['age_from']) : '';
$age_to = isset($_POST['age_to']) ? escape($_POST['age_to']) : '';
$studying = isset($_POST['studying']) ? escape($_POST['studying']) : '';
$query = "SELECT * FROM users WHERE 1=1";
if (isset($_POST['submit'])){
$addstring1 = $addstring2 = $addstring3 = $and1 = $and2 = $and3 = "";
$andcnt =3;
if($refined_gender != '')
$addstring1 = " gender = '$refined_gender'";
if($age_from != '')
$addstring2 = " age >= '$age_from'";
if($age_to != '')
$addstring3 = " age <= '$age_to'";
for($i=1;$i<=$andcnt;$i++)
${"and".$i} = ${"addstring".$i} != '' ? " AND" : "";
$query .= $and1.$addstring1.$and2.$addstring2.$and3.$addstring3;
}
$get_all_users = mysqli_query ($connect, $query);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Instead of this code:
htmlentities (strip_tags(#$_POST['gender']));
you should validate it, like so:
$gender = filter_input(INPUT_POST, 'gender', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[mf]$/i']]);
$ageFrom = filter_input(INPUT_POST, 'age_from', FILTER_VALIDATE_INT, [ 'default' => 1, 'min_range' => 1, 'max_range' => 100]);
$ageTo = filter_input(INPUT_POST, 'age_to', FILTER_VALIDATE_INT, [ 'default' => 1, 'min_range' => 1, 'max_range' => 100]);
$studying = filter_input(INPUT_POST, 'gender', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^(similar|different|same)$/i']]);
This is simpler and more secure.
Each input should be properly validated.
Avoid using #.
Once you have the values, you can concatenate them in to your query, like so:
$types = '';
$values = [];
$query = 'SELECT * FROM users';
$where = [];
// empty tests for both null (no data in input) and false (invalid data)
if (!empty($gender)) {
$where[] = 'gender = ?';
$types .= 's';
$values[] = &$gender;
}
if (!empty($ageFrom)) {
$where[] = 'age >= ?';
$types .= 'i';
$values = &$ageFrom;
}
if (!empty($ageTo)) {
$where[] = 'age <= ?';
$types .= 'i';
$values = &$ageTo;
}
if (!empty($studying)) {
$field = 'user_bio';
// Get the $user_bio value of the current user from the database
// Change the $user_bio into a regular expression collection of words
$regexp = '('.str_replace(' ','|',$user_bio).')';
// Set up the where
switch ($studying) {
case 'same':
$comparison = '= ?';
break;
case 'different':
$comparison = 'NOT REGEXP (?)';
break;
case 'similar':
$comparison = 'REGEXP (?)';
break;
}
$where[] = $field.' '.$comparison;
$types .= 's';
$values[] = &$user_bio;
}
if (count($where) > 0) {
$query .= ' WHERE '.implode(' AND ',$where);
}
// new mysqli ( host,
$mysqli = new mysqli('localhost','root','','stuff');
$stmt = $mysqli->prepare($query);
// This allows you to use a variable number of arguments with the prepared statement
// Note the use of the ampersands on the array assignment, this ensures they are passed by reference
$params = array_merge([$types],$values);
call_user_func_array([$stmt,'bind_param'],$params);
$stmt->execute();
// Bind a variable for each column
$stmt->bind_result($user_name);
while ($stmt->fetch()) {
var_dump($result);
}
(I'm not sure why the answers already provided don't address your question sufficiently.)
I'd approach it like this. First, get rid of that first query execution to pull all users. Instead, use just a single query.
Dynamically prepare the SQL text. Start the statement with the "SELECT ... FROM users". (We'll handle appending an ORDER BY as the last step.
I'd conditionally check each "filter", to see if I need to append a condition to the WHERE clause or not.
At the start of the SQL, we'll include a "WHERE 1=1".
$sql = "SELECT ... FROM users u"
$sql .= " WHERE 1=1";
The "WHERE 1=1" is basically useless. The optimizer is going to throw that away. The reason we add it is just to make our code easier later. We can just append our next filter with " AND condition", and not worry about whether this is the first one, and we need to use WHERE instead of AND.
We'll initialize a string and an array, to hold our bind types string "sssis" whatever it needs to be, and an array of references to the values we want to pass in.
$bind_type = "";
$bind_vals = array();
The processing for each filter is going to be icky... but we can do it. Check if we need to append anything to the SQL. If we do, figure out what needs to be added, including any bind placeholders. And append the type of the bind parameter ("i", "s", whatever) to the $bind_type string, and push (the reference to) a value into our $bind_vals array.
if ( $refined_gender ) {
// figure out what that SQL text needs to look like
// append the string to the SQL text
$sql .= " AND u.gender = ?";
// append type to string, and push a reference to the value into array
$bind_types .= "s";
$bind_val[] = &$refined_gender;
}
Our code in there is going to be more complicated than that. That's just handling an equality comparison. We're just keeping things simple now, to illustrate the pattern.
We repeat the same kind of thing for each filter we might need to add. Check if it's needed, figure out what we need to append to the SQL text, append to the bind_types string and push (a reference to) the value into the bind_vals array.
For working this out, I'd start with working on just one condition, and get that working, to get the kinks worked out. When we add more filters, and things go awry, I know where to look for the problem. (I know what was working before.)
When I'm done with the WHERE clause, I append any ORDER BY and LIMIT that I need. This could be conditional, but in the end, we're going to wind up doing something like this:
$sql .= " ORDER BY u.id DESC LIMIT 50";
When I'm done with all that, I've got a string containing SQL text that looks something like this:
SELECT ...
FROM users u
WHERE 1=1
AND u.gender = ?
AND u.age_from >= ?
AND u.age_to <= ?
ORDER BY u.id DESC
LIMIT 50
(in this example, it contains three bind placeholders. If we've done it right,
we'll have a $bind_types string containing three characters, e.g. "sii"
And we'll have a $bind_vals array that contains references to three values.
Now, we can call mysqli_stmt_prepare. If there's not an error in our SQL, we should get back a statement handle.
$stmt = mysqli_prepare($conn,$sql);
(Check the return from the prepare.)
Now we just need to bind our parameters. And this is where mysqli makes things a little hairy. If we were using PDO (or Perl DBI), calling the "bind parameter/bind value" would be easy. Those would let us pass an array of the bind values. But not mysqli. He won't let us call mysqli_stmt_bind_param with an array as an argument.
We need to run a function call like this:
mysqli_stmt_bind_param($stmt, $bind_types, &$refined_gender, &$age_from, ... );
And our problem is that we have a variable number of arguments.
There is a workaround.
We can use the call_user_func_array function.
Because the code is using procedural style and not object oriented style, the handle to the prepared statement is the first argument, the second argument is the bind types string, followed by the bind values. The bind values are already in an array. We just need to get all of those into one hugh jass array.
The array_merge function seems to be custom designed for doing this.
// array_merge(array($stmt), array($bind_types), $bind_vals)
That will return us a single array. Which is exactly what we need for calling the call_user_func_array function. We aren't going to need that array anywhere else (unless we're debugging, and we want to print it out).
We only need to call mysqli_stmt_bind_param if we have at least one bind placeholder in our statement. So we can shortcut around this if our $bind_types string is empty. (And we know $bind_types won't be "0" because our code never appended a "0" to it.)
if ($bind_types) {
call_user_func_array('mysqli_stmt_bind_param', array_merge(array($stmt), array($bind_types), $bind_vals) );
}
The first argument (to call_user_func_array) is the name of the function we want to execute, and the second argument is the hugh jass array that we want converted into a list.
And the whole point of doing that is making it dynamic, we can pass in one, two, three, bind values.
At this point, we're ready to execute the statement, and fetch the results.
Again, important to point out: mysqli_stmt_bind_param expects the bind values to be passed by reference, not by value. And that's why we pushed references to the values into the bind_vals array.
I'm not sure what question you asked.
But definitely ditch that first call to mysqli_query. That's going to return all rows in the users table.
With one or two conditions, the approach of static SQL and static bind types, and listing out the bind values is workable.
But when we get three, four, five possible filters, and all the possible combinations, that's going to be unweildy.
So we go with a more dynamic approach, dynamically creating the query, and pushing our bind values on an array as go.
This Html page:
<form method="POST" action="">
<input type="radio" name="rbo_gender" value="male">Male
<input type="radio" name="rbo_gender" value="female">Female
Age From<select name="agefrom">
<?php
for($i=10;$i<50;$i++):
?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php
endfor;
?>
</select>
Age To<select name="ageto">
<?php
for($i=10;$i<50;$i++):
?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php
endfor;
?>
</select>
Studying:
<input type="radio" name="rbo_type" value="similar">Similar
<input type="radio" name="rbo_type" value="exact">Exactly same
<input type="radio" name="rbo_type" value="different">Different
<input type="submit" name="btnsearch" value="Search">
</form>
This is php part:
if($_POST["btnsearch"])
{
if(!empty($_POST["rbo_gender"]))
{
$gender = $_POST["rbo_gender"];
$cond .= " and gender = '".$gender."'";
}
if(!empty($_POST["agefrom"]))
{
$agefrom = $_POST["agefrom"];
$cond .= " and age >= '".$agefrom."'";
}
if(!empty($_POST["ageto"]))
{
$ageto = $_POST["ageto"];
$cond .= " and age <= '".$ageto."'";
}
if(!empty($_POST["rbo_type"]))
{
$user_type = $_POST["rbo_type"];
switch($_POST["rbo_type"])
{
case "similar": $cond .= " and user_bio like '%".$ageto."%'";
break;
case "exact": $cond .= " and user_bio = '".$ageto."'";
break;
case "different":$cond .= " and user_bio ! like '%".$ageto."%'";
break;
}
}
$query = "select * from users where 1 ".$cond;
}
Please update query as per mysqli() & use bind param. Also instead of use # try to use filter_input you can use REGEXP instead of like also. I have created the variable to use bind_param purpose.

Creating a dynamic search query with PHP and MySQL

I'm trying to create a dynamic search query, based on the user input.
Requirements:
A user could fill in none, some, or all fields.
The query searches in a table for a record that matches all the requirements.
Now I have done my research, and I found out multiple ways on doing this. But none of them work, and if they do, they are far from practical.
Attempt:
At the moment I'm creating a query like this:
SELECT *
FROM assignments
WHERE (id = $id OR id = '')
AND (field1 = $field1 OR field1 = '')
This query works, but only if you fill in all the fields.
I got this from a stackoverflow article, that I can't find anymore, that said:
If the user has filled in an input field it will check the first rule
"id = $input"
and if the user hasn't specified any input it will check for "id = '' " and when it
checks for that, it will just return everything. Because it escapes the empty search rule.
But as you might already know, it doesnt work..
How would you suggest me to approach this?
Try getting all of the post vars and looping through them to see if they are valid, and then build your query
<?php
$id = $_POST[id];
$field1 = $_POST[field1];
$field2 = $_POST[field2];
$field3 = $_POST[field3];
$whereArr = array();
if($id != "") $whereArr[] = "id = {$id}";
if($field1 != "") $whereArr[] = "field1 = {$field1}";
if($field2 != "") $whereArr[] = "field2 = {$field2}";
if($field3 != "") $whereArr[] = "field3 = {$field3}";
$whereStr = implode(" AND ", $whereArr);
$query = "Select * from assignments WHERE {$whereStr}";
Something like that should handle what you need
You should start with a string like yours up to the WHERE statement, then after that you loop through all the fields the user wants to search with and add them to an array, then use the PHP function "implode" to glue the fields together with an AND statement as "glue".
Now add on the glued string to the startquery and voila!
I'd give example but on phone atm!
Building the query dynamically based on the responses is definitely a must. But another nice feature that allows users to find results based on even partial responses is using a MySQL REGEXP query. So for instance, if they wanted to find "maverick" in a Top Gun database, a query REGEXP = 'mav' | 'rick' would return results. This brings your search much closer to the search engine functionality that users are accustomed to.
Here's a REGEXP example, simplified.

Searching a MySQL table using PHP

I am trying to create a PHP file to help search a table built in MySQL from a webpage. I have built the form, which allows the user to enter keywords into two of the search criteria and a drop-down menu for the third. However, I am having trouble with the PHP file itself. I have appeared to do something wrong and cant quite figure out what is going wrong. If anyone can spot an error in the code below I'd really appreciate the help.
Thanks.
// define variables and set to empty values
$Location = $Commemorating = "";
if (isset($_GET['Region']) && !empty($_GET['Region']))
{
$Region_name = $_GET['Region'];
if (empty($_GET["Location"]))
{
$Location = "";
}
else
{
$Location = ($_GET["Location"]);
}
if (empty($_GET["Commemorating"]))
{
$Commemorating = "";
}
else
{
$Commemorating = ($_GET["Commemorating"]);
}
$query = "SELECT Monument,
Location,
Commemorating,
Region,
FROM MONUMENTS
WHERE Region = '$Region'";
//..if a location is specified run this query
if ($Location != "")
{
$query .= " AND Location LIKE '%$Location%'";
}
//..and if a name is entered run this query
if ($Commemorating != "")
{
$query .= " AND Commemorating LIKE '%$Commemorating%'";
}
//..and if a region is specified run this query
if ($Region != "All")
{
$query .= " AND Region LIKE '$Region'";
}
$query_run = mysql_query($query);
}
$query = "SELECT Monument,
Location,
Commemorating,
Region,
Looks like you should strip list comma in field list from the query:
$query = "SELECT Monument,
Location,
Commemorating,
Region
Like this.
There is a bit misunderstanding since you check is Region is not empty, then query for items in given Region and then add another cause in case of Region is not 'All'. So if I run your code with Region = 'All' then the query will return only the items that have Region set to 'All', which sounds a bit odd (I'd say monuments are at a single region, isn't it?).
You also use LIKE while may simple use = since you add sibgle quotes (') around strings so it won't give you any 'wildcard' match but slow down the query. Another thing to do is to do some mysql escape function to be sure you won't get SQL code in one of your GET query.
May I also suggest to short your code a bit:
$Region_name = isset($_GET['Region']) ? trim($_GET['Region']) : '';
if ($Region_name) {
$Location = isset($_GET['Location']) ? trim($_GET['Location']) : '';
$Commemorating = isset($_GET['Commemorating']) ? trim($_GET['Commemorating']) : '';
$query = sprintf("SELECT
Monument,
Location,
Commemorating,
Region
FROM MONUMENTS
WHERE 1=1%s%s%s",
$Region!='All' ? "AND Region='".mysql_real_escape_string($Region)."'",
$Location ? "AND Location='".mysql_real_escape_string($Location)."'",
$Commemorating ? "AND Region = '".mysql_real_escape_string($Region)."'",
);
...etc...
I add 1=1 so I can easily add AND to the following causes without worry.
Use $Region_name instead of $Region in your query. I see you depend on user input (via $_GET). Make sure you sanitize user input: https://stackoverflow.com/a/3126175/1071063

(PHP) MySQL select query with array from $_GET

What I'm trying to do is go from a search URL such as this:
search.php?president=Roosevelt,+F.&congress=&nomination_received_by_senate=&state=CT
To a MySQL query like this:
SELECT `name` FROM `nominations` WHERE president=`Roosevelt, F.` AND state=`CT`
I have some code that strips any empty values from the URL, so I have an array as such:
Array ( [president] => Roosevelt, F. [state] => CT )
Going from this to the SQL query is what is giving me trouble. I was hoping there might be some simple means (either by some variation of PHP's join() or http_build_query()) to build the query, but nothing seems to work how it needs to and I'm pretty lost for ideas even after searching.
Not sure if it would require some messy loops, if there is a simple means, or if the way I'm going about trying to accomplish my goal is wrong, but I was hoping someone might be able to help out. Thanks in advance!
Edit: To clarify, sometimes the inputs could be empty (as in the case here, congress and nomination_received_by_senate), and I'm hoping to accommodate this in the solution. And yes, I intend to implement means to avoid SQL injection. I have only laid out the basics of my plan hoping for some insight on my methods.
You could build up your query string like this if your GET params match your db fields:
$field_array = array('president', 'congress', 'nomination_received_by_senate', 'state');
$query = 'SELECT `name` FROM `nominations` WHERE ';
$conditions = array();
foreach($field_array as $field) {
$value = $_GET[$field];
if(empty($value)) continue;
$condition = mysql_real_escape_string($field) . '` = ';
$quote = '';
if(!is_numeric($value)) $quote = '"';
$condition .= $quote . mysql_real_escape_string($value) . $quote;
$conditions[] = $condition;
}
$query .= implode(' AND ', $conditions) . ';';
//perform query here...
To access the $_GET variables you could just do $_GET["president"] and $_GET["state"] and get the information. Make sure you sanitize the input.
$president = sanitize($_GET["president"]);
$state = sanitize($_GET["state"]);
$result = mysql_query("SELECT name FROM nominations WHERE president='".$president."' AND state='".$state"'");
Sanitize would be a function like mysql_real_escape_string() or your own function to clean up the input. Make sure you check if the $_GET variables are set using the isset() function.

Categories