I'm working on a Wordpress plugin to search through all the users by first name, last name, email etc. It is working as long as I only use 1 of the values like first name.
I need to add all the values to the select!
I already tried adding more by using ',' and OR statements but it isn't working.
$results = $wpdb->prepare("SELECT * FROM users WHERE first_name LIKE %s", "%".$_POST['search']."%");
EDIT: found it
Found it!
$results = $wpdb->prepare("SELECT * FROM users WHERE lower(first_name) LIKE lower (%s) OR lower(last_name) LIKE lower(%s) LIKE lower(%s)OR lower(postcode) LIKE lower(%s)", "%".$_POST['search']."%", "%".$_POST['search']."%");
To get a literal % to pass through $wpdb->prepare just double it. You don't need to be avoiding $wpdb->prepare.
Proof of concept:
var_dump($wpdb->prepare('SELECT * FROM {$wpdb->posts} WHERE post_title LIKE "%%%s%%"','Hello'));
So your query should be :
$results = $wpdb->prepare("SELECT * FROM users WHERE first_name LIKE %%%s%%",$_POST['search']);
(more...)
Update
Use this for imploding OR :
$var[] = 'name LIKE "%%%s%%"';
$var_data[] = 'Hello';
$var[] = 'email LIKE "%%%s%%"';
$var_data[] = 'tt#tt.tt';
$var[] = 'date LIKE "%%%s%%"';
$var_data[] = 'Howdy';
var_dump($wpdb->prepare('SELECT * FROM users WHERE '.implode(' OR ',$var),$var_data));
Are you treating the object properly? This would iterate over the values retrieved
while($row = $results->fetch_assoc()){
echo $row['username'] . '<br />';
}
Related
I have a basic query as follows
$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";
I have to modify this query to create a query where we have multiple subject codes fetched from an array.
$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....
Now I want to the original query to be modified something as follows
$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";
Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.
How can i accomplish this?
You can use a subquery like this:
$query = 'SELECT * FROM files
WHERE subject_code IN (
SELECT subject_code FROM subject WHERE sbranch = "' . $branch . '"
)';
You can use implode to convert array to string comma delimited
like below:
$branch_array = array('subject1', 'subject2', 'subject3');
$branch = implode("','", $subject_array );
$query1="SELECT subject_code FROM subject WHERE sbranch in ('".$branch."')";
result:
'subject1', 'subject2', 'subject3'
Hope that resolve your issue
You can use Mysql In operator
Like this
SELECT * FROM files WHERE subject_code in ('SC1','SC2')";
You can achieve ('SC1','SC2') by using implode php function,
like this:
$subCodes = implode("','", $subject_array );
SELECT * FROM files WHERE subject_code in ('".$subCodes ."')"
$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
$codes=(array)$result; //this will convert it in normal array. old school typecasting ;)
$codes=array_values($codes);
$query = "SELECT * FROM files WHERE subject_code in (".implode(",",$codes).")";
//considering result is an object of subject codes.
CODE UPDATED ABOVE as it is an object.
You don't need to append to the first query. Just build a new query using MySQL in operator and php implode function.
SELECT * FROM files WHERE subject_code in ('SC1','SC2')
You can amend your php array to comma delimited string of SubjectCodes.
then:
$query1="SELECT * FROM files WHERE subject_code in (".$NewString.") ";
$NewString will look something like this:
"'SC1', 'SC2', 'SC3'"
$result = array(0=>'SC1',1=>'SC2'); //this is your array
$branch = implode("','", $result );
$query .= "
SELECT * FROM files WHERE subject_code in ('".$branch."') "; //this is query
How make mysql search defined just by what is written in html form, by user, and if some form box is stayed empty, mysql should ignore it. For example:
$sql = "SELECT * FROM catalog WHERE name= '".$name."' AND publisher = '".$publisher."' ";
mysql_query($sql);
This query will display all rows where name and publisher are together. Now, what if user insert just name, and left publisher box empty. The idea is that php/mysql ignore empty form box, and display every row with inserted name. But it will not do that because $publisher will be undefined, and error emerges. How to tell musql to ignore $publisher? More generally, the question is: how to generate query that make searching defined by certain criteria if they exists, and if they don't how to just ignore it?
You can build up the sql programmatically. I am assuming you have escaped the values properly.
$sql = "SELECT * FROM catalog";
$wheres = array();
if (!empty($name)) {
$wheres[] = " name = '$name'";
}
if (!empty($publisher)) {
$wheres[] = " publisher = '$publisher'";
}
if (count($wheres)) {
$sql .= " WHERE " . implode (' AND ', $wheres);
}
//RUN SQL
Also have a read through this, you are using a deprecated mysql library.
This will allow either the name or the publisher to be NULL.
<?php
$sql = "SELECT * FROM catalog WHERE (name= '".$name."' OR name IS NULL) AND (publisher = '".$publisher."' OR publisher IS NULL)";
mysql_query($sql);
Try like
$my_var = " ";
if($publisher) //if(!empty($publisher))
$my_var = " AND publisher = '".$publisher."' ";
$sql = "SELECT * FROM catalog WHERE name= '".$name."' ".$my_var;
if the publisher is empty then you need to pass the NULL value and PLZ note that it is a bad practise.It will causes many sql injection issues.Try to put validations for the things
I have a php code with a query:
$query = "SELECT * FROM TDdb WHERE status = $status AND occupation =$occupation";
I am sending the values status and occupation with a client application to this php code.
This works when I send both status and occupation. But I want it to return rows if I just send status but not occupation also ( I mean no matter what the occupation is).
does anyone have any suggestions?
I would appreciate any help.
PS: I want to do it without if statement and just but changing the query
Personally I would create a base query and append conditions wherever you have them, like so:
$sql = 'SELECT * FROM TDdb';
$conditions = array();
$args = array();
if ($action) {
$conditions[] = 'status = :status';
$args[':status'] = $status;
}
if ($occupation) {
$conditions[] = 'occupation = :occupation';
$args[':occupation'] = $occupation;
}
if ($conditions) {
$sql .= ' WHERE ' . join(' AND ', $conditions);
}
$stmt = $db->prepare($sql);
$stmt->execute($args);
Looks like you've got a few good options for how to do it in SQL, or how to make the SQL string variable in PHP.
One reason to consider using an 'if' in the PHP code for the database access performance.
When you introduce an 'or' condition like that in SQL, you're not going to get index access. It is much harder for the database to determine what path it should take than for the PHP code because the SQL engine optimizes the query without knowing what the variable will resolve to at execution.
You already know in the PHP which version of the query you really want. This will perform better if you make that choice there.
This will work if you pass an occupation or a NULL value.
SELECT *
FROM TDdb
WHERE status = $status
AND ($occupation IS NULL OR occupation = $occupation)
"SELECT * FROM TDdb WHERE status = '$status' AND (occupation = '$occupation' OR occupation IS NULL)";
Apart from the solution provided by #Tom and #Damien Legros, you may create two query strings one with occupation and one without occupation. Something like:
$query = "SELECT * FROM TDdb WHERE status = $status";
if ($occupation != "") {
/*When you have value for occupation*/
$query .= " AND occupation =$occupation";
}
So in this case, data will be returned if you have only the status field. Secondly, please check if the status and occupation fields in table are varchar then you have to enclose them in single quotes (').
Thanks everyone for help. specially jack.
finally i created my query like this:
$query = 'SELECT * FROM TDdb';
if ($status) {
$query = $query." WHERE status = '".$status."'";
}
if ($occupation) {
$query = $query." AND occupation = '".$occupation."'";
}
i have a problem with php in the following:
$sql = 'SELECT name FROM chiled WHERE `im` LIKE $id ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0];
there is error in mysql_fetch_row($query);
but if i do the following :
$sql = 'SELECT name FROM chiled WHERE `im` LIKE 1111 ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0];
it is working and prints the name
can you please tell me what is wrong?
Single quotes in PHP doesn't evaluate embedded variables - you need to use double quotes to do that. (See the "Single quoted" section of the PHP Strings manual page for more info..)
i.e.: $sql = "SELECT name FROM chiled WHERE 'im' LIKE $id ";
Or better still...
$sql = 'SELECT name FROM chiled WHERE im="' . mysql_real_escape_string($id) . '"';
(As you're not using the % in your like, you're presumably not attempting to do any form of pattern matching.)
Additionally, I'd recommend a read of the existing Best way to stop SQL Injection in PHP question/answers.
Are you sure you want to be using LIKE? It looks more to me like you want to see if im = $id. Also, make sure you're escaping your variables before using them in the query.
Edit
If you DO want to us LIKE, you probably want something like this:
$sql = "SELECT name FROM chiled WHERE `im` LIKE '%$id%' ";
which will find anywhere that the string $id is found in the im column.
You need to quote the variable after LIKE, like this:
$sql = "SELECT name FROM chiled WHERE im LIKE '$id'";
$query = mysql_query($sql);
$a = mysql_fetch_row($query);
echo $a[0];
// ....
Beside, you are using single quotes, Therefore, $id is not replaced for its value. Your query look like this:
SELECT name FROM chiled WHERE im LIKE $id;
$sql = "SELECT name FROM chiled WHERE `im` LIKE '$id' ";
change to double quotes - http://php.net/manual/en/language.types.string.php
I'm trying to build a query using php and mysql,
$query = "select * from products where product_name = '$item_name'";
this works when $item_name holds only one name, but $item_name is an array and based on the user's interaction can contain multiple names, how can I make the query to run for multiple name and get the resulted rows.
Thanks in advance
Here's how you could build a safe list of names for inserting into an IN clause...
if (is_array($names) && count($names))
{
$filter="('".implode("','" array_map('mysql_real_escape_string', $names))."')";
$sql="select * from products where product_name in $filter";
//go fetch the results
}
else
{
//input was empty or not an array - you might want to throw an
//an error, or show 'no results'
}
array_map returns the input array of names after running each name through mysql_real_escape_string to sanitize it. We implode that array to make a nice list to use with an IN clause.
You should always ensure any data, particularly coming directly from the client side, is properly escaped in a query to prevent SQL injection attacks.
$vals = implode(',',$item_name);
$query = "select * from products where product_name in (".$vals.");";
Give that a try.
$query = "select * from products where product_name in(";
foreach($item_name as $name)
{
$query .= "'" . $item_name . "', ";
}
$query = substr($query, 0, strlen$query) - 2);
$query .= ");";
First answer (by inkedmn) is really the best one though
foreach($item_name as $name) {
$query = "select * from products where product_name = '$name'";
//whatever you want to do with the query here
}
something like that ought to do it.
Based on inkedmn's response (which didn't quote the item names):
$query = 'select * from products where product_name in ("' . implode('", "', $item_name ) . '")';
Although you may be better with a fulltext search.
http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html