Multipurpose search in sql php - php

I want to search based on multiple values, but in SQL I don't know how to search based on the second value when one of these values is empty.
Can anyone help me?
This is the SQL that I reached, but I didn't get an answer
$sql = "SELECT * FROM $table_homes WHERE title LIKE '%$title%' AND city='$city' AND type_home='$type'";

if title/city/type has a value, add to the query
$and = "";
if ($title){
$and .= " AND title LIKE '%$title%'";
}
if ($city){
$and .= " AND city LIKE '%$city%'";
}
if ($type){
$and .= " AND type_home LIKE '%$type%'";
}
$sql = "SELECT * FROM $table_homes WHERE 1=1 $and";

Related

PHP to create MySQL query from URL query

I have a relatively small search form that I want people to use to search my SQL database.
The only way I've done this before was with a billion nested if statements. Is there a better way to do this?
I am parsing my URL query string, so I have my variables of say:
$city
$bedrooms
$elementaryschool
If I were to just try to try:
$sql = "SELECT * FROM $table_name WHERE ";
if(isset($city)) {
$sql .= " `City` LIKE " . $city;
}
if(isset($bedrooms)) {
$sql .= " AND `Bedrooms` >= " . $bedrooms;
}
if(isset($elementaryschool)) {
$sql .= " AND `ElementarySchool` = " . $elementaryschool;
}
Then I run into an issue when $city isn't set because my query ends up with "SELECT * FROM $table_name WHERE AND Bedrooms >= $bedrooms"
That wouldn't exactly work. What are my options?
I completely understand how to do it if I am including all parameters in my query, which seems to be what all previous questions have asked. But how do I do this when not all fields will have a value? I have a total of 12 possible fields to use for searching, and they can search by just 1 or by all 12.
As I mentioned before, all of the questions I have been able to find refer to coming up with one static SQL query, instead of one that will have varying number of parameters.
I would go with:
$sql = "SELECT * FROM $table_name";
$where = array();
$params = array();
and then:
if(isset($city)) {
$where[] = "City LIKE ?";
$params[] = $city;
}
if(isset($bedrooms)) {
$where[] = "Bedrooms >= ?";
$params[] = $bedrooms;
}
if(isset($elementaryschool)) {
$where[] = "ElementarySchool = ?";
$params[] = $elementaryschool;
}
and finally:
if(!empty($where)) {
$sql .= "WHERE " . implode(" AND ", $where);
}
$result = $db->prepare($sql)->execute($params);
PLEASE NOTE that here, since I do not know what kind of database layer/abstraction you are using, $db represents the database connection, prepare() is used to create a prepared statement, and execute() tu run it, as you would do using PDO; this also protects against SQL injection.

Dynamic sql search in php

Trying to create a dynamic search functionality.
Goal : allowing user to search by email (if not empty), if empty (by last name), if both are not empty, than by both, etc.
I know I can write if statement depicting every scenario and than insert SQL command based on that, question is can this be handled in a more simplified manner. Thanks for your help.
Current function set up does OR across all fields, values are coming from $_POST:
find_transaction($email,$last_name,$first_name, $transaction_id)
{
GLOBAL $connection;
$query = "SELECT * ";
$query .= "FROM transactions WHERE ";
$query .= "email='{$email}' ";
$query .= "OR last_name='{$last_name}' ";
$query .= "OR first_name='{$first_name}' ";
$query .= "OR transaction_id='{$transaction_id}' ";
$query .= "ORDER BY date DESC";
$email = mysqli_query($connection,$query);
confirm_query($email);
return $email;
}
I do this all the time, it's not too much work. Basically build your WHERE statement dynamically based off your POST variables, using a series of if statements.
For example:
$where_statement = "";
// First variable so is simpler check.
if($email != ""){
$where_statement = "WHERE email = '{$email}'";
}
// Remaining variables also check if '$where_statement' has anything in it yet.
if($last_name != ""){
if($where_statement == ""){
$where_statement = "WHERE last_name = '{$last_name}'";
}else{
$where_statement .= " OR last_name = '{$last_name}'";
}
}
// Repeat previous 'last_name' check for each remain variable.
SQL statement would change to:
$query = "SELECT * FROM transactions
$where_statement
ORDER BY date DESC";
Now, the SQL will only contain filters depending on what values are present, so someone puts in just email, it would generate:
$query = "SELECT * FROM transactions
WHERE email = 'smith#email.com'
ORDER BY date DESC";
If they put in just last name, it would generate:
$query = "SELECT * FROM transactions
WHERE last_name = 'Smith'
ORDER BY date DESC";
If they put both, would generate:
$query = "SELECT * FROM transactions
WHERE email = 'email#email.com' OR last_name = 'Smith'
ORDER BY date DESC";
Etc., etc.
You could add as many variables you wish here, and basically if the specific variable is not blank, it will add it to the "$where_statement", and depending on if there is anything in the "$where_statement" yet or not, it will decide to start with = "WHERE ", or append .= " OR" (notice the '.=' and the space before 'OR'.
Better use Data Interactive table : http://datatables.net/
It's useful and no SQL-injection :) Good luck !

How can I use multiple values in a "where" clause? [duplicate]

This question already has answers here:
MySQL query check two value in one column
(2 answers)
Closed 2 years ago.
My code and my database are the following
$my=mysql_query("select * from users where email='ids'")or die(mysql_error);
id___email___________pass
1 abc#d.com 123
2 xxx#x.uk 333
3 ah#cc.com 555
I need a syntax in which I will select * where id='1 , 3' and when I will echo $row[email] it will return
abc#d.com
ah#cc.com
Found the correct syntax:
$all=mysql_query("select * from users where id IN ('1','2','3')");
while($row = mysql_fetch_assoc($all))
{
echo $row['name'];
}
Use IN clause to get records for multiple emails.
$my=mysql_query("select * from users where email IN ('$email','$email2','$email3')")
or die(mysql_error);
Another, not optimal, solution is adding several options to the "where" clause.
Uses more resources, but, sometimes, is what you need.
By the way, I strongly, suggest put you SQL in a variable, first.
$myquery = "select * from users ";
$myquery .= "where (1 = 0) "; // defaults to false
$myquery .= "or (email='$email') "; // maybe true
$myquery .= "or (email='$email2') "; // maybe true
$myquery .= "or (email='$email3') "; // maybe true
$mydataset = mysql_query($myquery) or die(mysql_error);
There multiple "or" expression with a "=" string comparison, are the non optimal, more resources used, equivalent of the "in" operator.
Yet, sometimes is useful to know, or use, this equivalent. If you are not sure if the source string is case sensitive, or you want to trim the value for unwanted spaces, you could also replace the "=" operator by the "like" operator.
$email = trim($email);
$email2 = trim($email2);
$email3 = trim($email3);
$myquery = "select * from users ";
$myquery .= "where (1 = 0) "; // defaults to false
$myquery .= "or (email like '%$email%') "; // maybe true
$myquery .= "or (email like '%$email2%') "; // maybe true
$myquery .= "or (email like '%$email3%') "; // maybe true
$mydataset = mysql_query($myquery) or die(mysql_error);
Cheers.

How to use multiple HTML select tags make an SQL query

What I'm trying to do is create a form where the user selects an option from 2 'select' tags and then the value from the select tags is used for an SQL query (i.e results.php?select=option1+option2). I've already managed to make it so that one of the values is used in the query, however I can't get it so that both values are used in the query.
This is my code so far:
$input = $_GET['input']; //this is for the text input - ignore
$topic = $_GET['topic']; // the first select box value which works well
$location = $_GET['location']; //the second select box value which isnt being inserted into the query
$combined = $input . $topic . $location;
$terms = explode(" ", $combined);
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
Why are you combining the terms then splitting them again? :/. There's no need to. You are also separating strings using a " " but if there is no spacing between the text the array will take both values as one
$input = $_GET['input']; //this is for the text input - ignore
$topic = $_GET['topic']; // the first select box value which works well
$location = $_GET['location'];
$terms[]=$input;
$terms[]=$topic;
$terms[]=$location;
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
if ($each != $terms[count($terms)-1]) //If $each is not the last item in the array
$query .= "keywords LIKE '%$each%' ";
else
$query .= " OR keywords LIKE '%$each%' ";
}

SELECT MYSQL record containing 2 possible values

I would like to Select rows where a value is being returned. If they have chosen Male or Female in the select box, I would want it to search for that. That part is working fine. However, if they choose Either, I want it to say that MySQL should look if the column contains Male or Female and return any results.
Please note that I do not want to use OR statements inside the query if possible based on how the code is being written out.
I tried the below, but it did not seem to work. The values are coming from a select box in a form which has Either, Male or Female.
if ($postgender == "either")
{
$male = "Male";
$female = "Female";
$postgenderuse = ($male || $female);
}
else {
$postgenderuse = $postgender;
}
$query4 = mysql_query("SELECT * FROM tennis WHERE gender='$postgenderuse' ORDER BY playerid DESC LIMIT 0,20");
start creating the query from statements, also check if the form is sending one of the 3 values (just to make sure)
if ($postgender == "Either")
{
$postgenderuse = " ( `gender`='Male' OR `gender`='Female' ) ";
}
elseif ($postgender == "Male" || $postgender == "Female") {
$postgenderuse = " `gender`='".$postgender."' ";
}
else {
die('Error, no gender selected');
}
$query4 = mysql_query("SELECT * FROM `tennis` WHERE ".$postgenderuse." ORDER BY `playerid` DESC LIMIT 0,20");
Assuming that you're treating gender in binary terms, as consisting of only two options (Male, Female):
$sql = "SELECT * FROM tennis";
if(in_array($postgender, array("Male", "Female"))
{
$sql .= " WHERE gender=".$postgender;
}
$sql .= " ORDER BY playerid DESC LIMIT 0,20)";
$query4 = mysql_query($sql);
if It is either, then change your query to do a wild card search.
SELECT * FROM tennis WHERE gender LIKE '$postgenderuse'
That way, when they choose either, you can set postgenderuse to a % Sign.
Although, it might be a better idea to just use OR in your query, and build your query off of conditions, like:
if($postgender == "Male") {
$condition = "WHERE gender='Male'";
} else if($postgender == "Female") {
$condition = "WHERE gender='Female'";
} else {
$condition = "";
}
$query = "SELECT * FROM tennis " . $condition . " ORDER BY BLAH";
In anycase, either way should work. Being able to construct queries from conditionals is part of the power of php.
~ Dan
The solution you have tried would work if you were using Bitwise instead of String for the field gender.
What I suggest, is to use the SQL IN function.
Something like:
$query = "SELECT * FROM tennis WHERE gender IN ('" + implode("', '", $postGenderArray) + "')";

Categories