When I replace
$ordering = "apples, bananas, cranberries, grapes";
with
$ordering = "apples, bananas, grapes";
I no longer want cranberries to be returned by my query, which I've written out like this:
$query = "SELECT * from dbname where FruitName LIKE '$ordering'";
Of Course this doesn't work, because I used LIKE wrong. I've read through various manuals that describe how to use LIKE and it doesn't quite make sense to me.
If I change the end of the db to "LIKE "apples"" that works for limiting it to just apples. Do I have to explode the ordering on the ", " or is there a way to do this in the query?
LIKE is normally used for partially matching strings, e.g. you'd use
WHERE fruitname LIKE 'app%'
to find 'apple' and 'apples'.
What you (probably) want is the IN clause, e.g.
WHERE fruitname IN ('apples', 'bananas', 'grapes')
It probably should be:
SELECT * FROM database WHERE FruitName IN ('apples','bananas','grapes')
You need to explode the string and convert it to the appropriate SQL. This is probably the SQL syntax you want to end up with:
SELECT * FROM dbname WHERE FruitName IN ('apples', 'bananas', 'grapes')
PHP code:
$fruits = array();
foreach (explode(', ', $ordering) as $fruit) {
$fruits[] = "'" . mysql_real_escape_string($fruit) . "'";
}
$fruits = implode(', ', $fruits);
$sql = "SELECT * FROM dbname WHERE FruitName IN ($fruits)";
try using
SELECT * from dbname WHERE FruitName IN ('apples','bananas','grapes')
if you need the result to be in the same order as the IN list extend the query with and ORDER BY
SELECT * from dbname WHERE FruitName IN ('apples','bananas','grapes') ORDER BY FruitName
Related
I know how to perform an SQL LIKE % query for a single value like so:
$sql = "SELECT * FROM Farmers WHERE Available_products LIKE ('%Bananas%')";
but how do I do this if the search terms for my LIKE comes from an array? For example, let's say we have an array like this:
$_POST['Products']="Cacaos,Bananas";
$array=implode(',', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE Available_products LIKE ('%$array%')";
I want to get all the records in database that the column Available_Products contains Cacaos or Bananas or Both
Convert the array to a regular expression and use REGEX instead of LIKE
$_POST['Products'] = array('Cacaos', 'Bananas');
$regex = implode('|', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE Available_products REGEX :regex";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':regex', $regex);
$stmt->execute();
You can try with the help of REGEXP .
$_POST['Products']="Cacaos,Bananas";
$array=implode('|', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE
Available_products REGEXP". $array;
You can also do something like :
// Populating join table.
CREATE TABLE temp_table_myArray (myArray nvarchar(255));
INSERT INTO temp_table_myArray (myArray) VALUES ('Cacaos');
INSERT INTO temp_table_myArray (myArray) VALUES ('Bananas');
// Query using the join table.
SELECT F.*
FROM Farmers AS F
INNER JOIN temp_table_myArray AS T ON (F.Available_products LIKE(CONCAT('%',T.myArray,'%')));
But I think there is a better PHP way to solve your problem...
I want to select record from table with key.My code is working but it's not select all record regarding Php and Mysql it select only PHP,Mysql record.
My code is
$skill=PHP,Mysql;
mysql_query("select * from tablename(skill) where fieldname(key) like '%$skill%'");
Try to do this
mysql_query("select * from skill where (key like '%PHP%' OR key like '%Mysql%')");
As you have comma separated values in $skill variable like operator will not work correctly, try using following query
select * from skill where FIND_IN_SET(keyn,'$skill')
Demo sql fiddle at http://sqlfiddle.com/#!2/181c74/5
$skill="PHP,Mysql";
mysql_query("select * from skill where key like '%$skill%'");
I am assuming you want to search for records that contain "PHP", "MySQL", or both. What you're doing is searching for the exact string of "PHP,MySQL".
A quick and dirty solution would be to turn $skill into an array that is split on the commas and then perform the search for each term using the OR keyword.
For example:
$skill = array("PHP", "MySQL");
$query = "select * from tablename(skill) where ";
foreach ($skil in $skill)
$query . "fieldname(key) like '%$skil%' OR ";
//code to remove the OR at the very end
Use in into your Query
select * from `skills` WHERE skillslist in ('Php','Javascript')
Run demo Fiddle
I currently use a mysql statement like the one below to search post titles.
select * from table where title like %search_term%
But problem is, if the title were like: Acme launches 5 pound burger and a user searched for Acme, it'll return a result. But if a user searched for Acme burger or Acme 5 pound, it'll return nothing.
Is there a way to get it to return results when a users searches for more than one word? Is LIKE the correct thing to use here or is there something else that can be used?
You could use a REGEXP to match any of the words in your search string:
select *
from tbl
where
title REGEXP CONCAT('[[:<:]](', REPLACE('Acme burger', ' ', '|'), ')[[:>:]]')
Please notice that this will not be very efficient. See fiddle here.
If you need to match every word in your string, you could use a query like this:
select *
from tbl
where
title REGEXP CONCAT('[[:<:]]', REPLACE('Acme burger', ' ', '[[:>:]].*[[:<:]]'), '[[:>:]]')
Fiddle here. But words have to be in the correct order (es. 'Acme burger' will match, 'burger Acme' won't). There's a REGEXP to match every word in any order, but it is not supported by MySql, unless you install an UDF that supports Perl regexp.
To search for a string against a text collection use MATCH() and AGAINST()
SELECT * FROM table WHERE MATCH(title) AGAINST('+Acme burger*')
or why not RLIKE
SELECT * FROM table WHERE TITLE RLIKE 'Acme|burger'
or LIKE searching an array, to have a compilation of $keys
$keys=array('Acme','burger','pound');
$mysql = array('0');
foreach($keys as $key){
$mysql[] = 'title LIKE %'.$key.'%'
}
SELECT * FROM table WHERE '.implode(" OR ", $mysql)
What you need to do is construct a SQL such that, for example:
select * from table where title like "%Acme%" and title like "%burger%"
In short: split the string and create one like for each part.
It might also work with replacing spaces with %, but I'm not sure about that.
The best thing is thing use perform union operation by splitting your search string based on whitespaces,
FOR Acme 5 pound,
SELECT * FROM TABLE WHERE TITLE LIKE '%ACME 5 POUND%'
UNION
SELECT * FROM TABLE WHERE TITLE LIKE '%ACME%'
UNION
SELECT * FROM TABLE WHERE TITLE LIKE '%5%'
UNION
SELECT * FROM TABLE WHERE TITLE LIKE '%POUND%'
Find out a way to give the first query a priority. Or pass the above one as four separate queries with some priority. I think you are using front end tp pass query to data bases, so it should be easy for you.
<?php
$search_term = 'test1 test2 test3';
$keywords = explode(" ", preg_replace("/\s+/", " ", $search_term));
foreach($keywords as $keyword){
$wherelike[] = "title LIKE '%$keyword%' ";
}
$where = implode(" and ", $wherelike);
$query = "select * from table where $where";
echo $query;
//select * from table where title LIKE '%test1%' and title LIKE '%test2%' and title LIKE '%test3%'
I have a couple of situations where I have an array of input, such as:
$myArray = array( "apple", "banana", "orange", "pear" );
Where the array could have any number of fruits in it. I want to use MySQL prepared statements in PHP to create a query similar to:
SELECT * FROM fruitcart WHERE fruitname IN ('apple','banana','orange','pear');
Previously, I was accomplishing this by doing something like:
$query = "SELECT * FROM fruitcart WHERE fruitname IN ('" . implode( "','", $myArray ) . "')";
but I'd like to know if there is a way I could do something similar with prepared statements?
There is no way to do that with a prepared statement. The only possibility is to do something like this:
$query = "SELECT * FROM fruitcart WHERE fruitname = ? OR fruitname = ? OR fruitname = ? ...
You can easily build a statement like this with an foreach loop.
But be aware that, since your array will probably have different amounts of values, this might cause some confusion in the database optimizer algorithms. For optimal performance you might want to prepare statements with for example 128, 64, 32, 16, 8, 4, 2, 1 slots and then use the biggest one you can fill until you got all your values from the database. That way the optimizer is able to deal with a much more limited amount of statement skeletons.
You can also use a temporary table for this. For example create a table that only contains the values (apple, banana, ...) and an id for your value set.
You can then insert the array of values into the database using a unique set-id (php offers a guid function for example) and then selecting them in a subquery:
$query = "SELECT * FROM fruitcart WHERE fruitname IN (SELECT fruitname FROM temptable WHERE setid = ?)"
That's easily preparable and will perform quite good.
You can use an in-memory table for the temptable so it will be very fast.
$placeholders = rtrim(str_repeat('?, ', count($myArray)), ', ') ;
$query = "SELECT * FROM fruitcart WHERE fruitname IN ($placeholders)";
$stm = $db->prepare($query) ;
$stm->execute($myArray) ;
You are using the proper way to do that, you can edit
$list = implode( ',', $myArray );
$query = "SELECT * FROM fruitcart WHERE fruitname IN ('" . $list . "')";
That's it :)
This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 11 months ago.
I have and array with two values and I want to use it with sql IN operator in select query.
Here is the structure of my table
id comp_id
1 2
2 3
3 1
I have an array $arr which have two values Array ( [0] => 1 [1] => 2 )
I want to fetch the record of comp_id 1 and comp_id 2. So I wrote the following query.
SELECT * from table Where comp_id IN ($arr)
But it does not return the results.
Since you have plain integers, you can simply join them with commas:
$sql = "SELECT * FROM table WHERE comp_id IN (" . implode(',', $arr) . ")";
If working with with strings, particularly untrusted input:
$sql = "SELECT * FROM table WHERE comp_id IN ('"
. implode("','", array_map('mysql_real_escape_string', $arr))
. "')";
Note this does not cope with values such as NULL (will be saved as empty string), and will add quotes blindly around numeric values, which does not work if using strict mysql mode.
mysql_real_escape_string is the function from the original mysql driver extension, if using a more recent driver like mysqli, use mysqli_real_escape_string instead.
However, if you just want to work with untrusted numbers, you can use intval or floatval to sanitise the input:
$sql = "SELECT * FROM table WHERE comp_id IN (" . implode(",", array_map('intval', $arr)) . ")";
you need to convert the array into comma-separated string:
$condition = implode(', ', $arr);
And, additionally, you might want to escape the values first (if you are unsure about the input):
$condition = implode(', ', array_map('mysql_real_escape_string', $arr));
$arr is a php array, to the sql server you need to send a string that will be parsed
you need to turn your array in a list like 1, 2, etc..
to do this you can use the function http://php.net/implode
so before running the query try
$arr = implode ( ', ', $arr);
You need to implode your array with ',' comma
$imploded_arr = implode(',', $arr);
SELECT * from table Where comp_id IN ($imploded_arr)
you can only pass string to mysql as query, so try this
mysql_query("SELECT * FROM table WHERE comp_id IN (".implode(',',$arr).")");
All the people here are proposing the same thing but i got a warning in WordPress because of a simple error. You need to add commas to your imploded string. To be precise something like this.
$query = "SELECT *FROM table Where comp_id IN ( '" . implode( "', '", $sanitized_brands ) . "' )";
Hoping it helps someone like me. :)
You're mixing PHP and SQL - for the IN SQL operator, you need a format like:
SELECT * from table WHERE comp_id IN (1,2)
So to get that in PHP you need to do something like:
$sql = "SELECT * from table Where comp_id IN (".implode(',',$arr).")"
Bear in mind that this only works if the array comprises of integers. You have to escape each element if they are strings.
You need something like:
$sql = "SELECT * from table where comp_id in (".implode(',',$arr.")";
You need to actually convert your $arr to a string. The simplest way with what you're doing would be to use implode()
$query = 'SELECT * from table Where comp_id IN (' . implode(',', $arr) . ')';
Right now if you echo your query you'll see that rather than the array being in the IN statement, it will just be the word "Array"
You need to convert the array to a string for use in the query:
$list = implode(',', $arr);
Then it can be used in the IN clause:
SELECT * from table Where comp_id IN ($list)
As per #barryhunter 's answer which works only on array that contains integer only:
$sql = "SELECT * from table Where comp_id IN (".implode(',',$arr).")";
I've made some tweaks to make it work for array of strings:
$sql = "SELECT * from table Where comp_id IN ('".implode("','",$arr)."')";
There are some risks of SQL injection in a few of the previous answers. It might be fine if you are completely certain about $arr being sanitized (and will stay that way). But if you aren't completely sure, you might want to mitigate such risk using $stmt->bindValue. Here is one way of doing it:
# PHP
$in_list = array();
for ($i = 0; $i < count($arr); $i++) {
$key = 'in_param_' . i;
$in_list[':' . $key] = array('id' => $arr[$i], 'param' => $key);
}
$keys = implode(', ', array_keys($in_list));
// Your SQL ...
$sql = "SELECT * FROM table where id IN ($keys)";
foreach ($in_list as $item) {
$stmt->bindValue($item['param'], $item['id'], PDO::PARAM_INT);
}
$stmt = $this->getConnection()->prepare($sql)->execute();
If your array is of Integers :
$searchStringVar = implode(",",$nameIntAryVar);
$query="SELECT * from table NameTbl WHERE idCol='$idVar' AND comp_id IN ($searchStringVar)";
If your array is of Strings :
$searchStringVar = implode("','",$nameStringAryVar);
$query="SELECT * from table NameTbl WHERE idCol='$idVar' AND comp_id IN ('$searchStringVar')";