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.
Related
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";
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 !
Hello I have 3 fields on input form which are set via POST method to external php
$id=$_POST['id'];
$nombre=$_POST['nombre'];
$cedula=$_POST['cedula'];
where I would like to make a search option depending on which field have data inside it or if a user put data in all 3 or in only 2 fields to search from the input fields which are not NULL fields in the same table where there is a result.
my sql query is something like that $sql = "SELECT * FROM users WHERE userID = $id AND nombre = $nombre AND cedula = $cedula) ";
obviosly which is not working, what should I do to make it work. Do I need to change only the query or I need to put something before it to check first what is not NULL. Thanks
Firstly, your SQL statement should be updated to have enclosed ' (commas) around string values.
So, modify it to:
$sql = "SELECT * FROM users WHERE userID = '$id' AND nombre = '$nombre' AND pass = '$pass'";
// ----------------------------------------^---^--------------^-------^------------^-----^
Second thing is that you should search a field only when it has a value otherwise, it of no use.
So, your modified PHP code should be:
$sql = "SELECT * FROM users WHERE 1 ";
if (!empty($id)) {
$sql .= " AND userID = '$id' ";
}
if (!empty($nombre)) {
$sql .= " AND nombre= '$nombre' ";
}
if (!empty($pass)) {
$sql .= " AND pass= '$pass' ";
}
And your Database will be searched for the fields only if they have data filled in the form.
Try to add quote:
$sql = "SELECT * FROM users WHERE userID = ".$id." AND nombre = ".$nombre." AND pass = '".$pass."' ";
Yes, you will need to put a check before which will ignore the fields which are null.
Also, you would need to put the $variable inside single quotes ' if they are VARCHAR or CHAR types.
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) + "')";
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 8 years ago.
What does the following line mean, particularly the operator .=?
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
in the code
<?php
$conn = pg_pconnect("dbname=publisher");
// these statements will be executed as one transaction
$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
pg_query($conn, $query);
?>
It seems to make some sort of array such that the last command processes first the first query and then the second.
This is the concatenate assignment operator. It will concatenate or add to the end of the string. So:
$a = "Hi!";
$a .= " I";
$a .= " love";
$a .= " StackOverflow";
$a .= " a";
$a .= " lot";
echo $a; // echos "Hi! I love StackOverflow a lot"
In your case
$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
echo $query;
/* echos "UPDATE authors SET author=UPPER(author) WHERE id=1; UPDATE authors SET author=LOWER(author) WHERE id=2; */
It means $query = $query . "UPDATE authors SET author=LOWER(author) WHERE id=2;";
So it appends the String to the Query Variable.
Your question is about the operator .=. It is a shorthand to a string concatenation followed by an assignment.
On assigment by operation operators
There is a family of operators we can call assignment by xyz, where xyz here represents a binary operation on operands of the same type, such as addition, subtraction, concatenation.
So, let's say we have an operator ⊕: int*int → int, meaning that it takes a pair of ints and produces another one:
⊕(a, b) = a ⊕ b
Let's say we want to calculate a⊕b and store the results on the variable a. We can do so by:
a = a ⊕ b
But we do this so often when coding that an operator was created to represent the line above. You should take it as a single operation that does both the ⊕ operation and the assignment ( = ) with a single call:
a ⊕= b ⇔ a = a ⊕ b.
Some examples
So, in your case, you have a .= operator. Now that you know about assignment by operation operators, you can guess that:
$query = "Hello, "
$query .= "World!";
is the same as:
$query = "Hello, "
$query = $query . "World!";
See?
Now, another frequent use of this kind operators are the += and -= versions.
However, abuse of this kinds of operators may lead to less readable code (especially when dealing with "low level" operators acting on bits, for example).
.= simply means "append". This
$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
…results in
$query == "UPDATE authors SET author=UPPER(author) WHERE id=1;UPDATE authors SET author=LOWER(author) WHERE id=2;"
it separates the updates with ; and executes both of them
Concatenates the string... so $query becomes:
"UPDATE authors SET author=UPPER(author) WHERE id=1;UPDATE authors SET author=LOWER(author) WHERE id=2;"