Select statement with where clause Like in array - php

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...

Related

MySQL select query comma separated numbers filter result

My table look like this:
Table screenshot
Here I'm getting the result by query:
$subject_ids = implode(',', $_POST['subject_ids'])
SELECT * FROM table WHERE focusarea LIKE '%$subject_ids%' ;
The result is perfect, but there is nothing to display when I select more than one subject ids, like if selecting only one then it shows,
but when to select 1, 2, and 4, but there is nothing with this LIKE query...
How can I fix this?
Use implode like,
PHP
$subject_id_aray = explode(",",$_POST['subject_ids']);
$in_array_string = array();
foreach($subject_id_aray as $values){
$in_array_string[] = "'".$values."'";
}
MySql
$sql = "SELECT * FROM table WHERE focusarea in (".implode(",",$in_array_string).") ;";
LIKE clause will not work in your case because using LIKE '%1,2,3%' in query will not get anything, as you as using Ids you should use IN instead of LIKE. LIKE will be used separately for each id if it is string.
As you are getting $_POST['subject_ids'] as an array, query will be like
$subject_str = implode(',', $_POST['subject_ids']);
$sql = "SELECT * FROM table WHERE focusarea IN($subject_str)";
If your column focusarea is not integer then
$subject_str = "'".implode("','", $_POST['subject_ids'])."'";
$sql = "SELECT * FROM table WHERE focusarea IN($subject_str)";
Maybe you have bug in POST.
Try to echo, $subject_ids befor inject to SQL.
You focus are is simple string of numbers, connected by ,, but what you are sending by POST maybe is not correct.
Other problem, this don't look like you full code.
Provide you file, if this don't resolve problem.

Check if specific value exists in mysql column

I have mysql column called categories. It can contain single or multiple values like this: 1 or 2 or 1,2,3 or 2,12...
I try to get all rows containing value 2.
$query = "SELECT * FROM my_table WHERE categories LIKE '2'";
$rows = mysql_query($query);
This returns row if column only has value 2 but not 1,2,3 or 2,12. How I can get all rows including value 2?
You can use either of the following:
% is a wildcard so it will match 2 or 1,2, etc. Anything on either side of a 2. The problem is it could match 21, 22, etc.
$query = "SELECT * FROM my_table WHERE categories LIKE '%2%'";
Instead you should consider the find_in_set mysql function which expects a comma separated list for the value.
$query = "SELECT * FROM my_table WHERE find_in_set('2', `categories`)";
Like #jitendrapurohut said, you can do it using
$query = "SELECT * FROM my_table WHERE categories LIKE '%2%'";
$rows = mysql_query($query);
But is really bad to store collections like this. A better aproach is as follow:
categories(id_c, name) => A table with each category
my_table(id_m [, ...])
categories_my_table(id_c, id_m)
Then use this query:
SELECT *
FROM my_table m
INNER JOIN categories_my_table cm ON m.id_m = cm.id_m
INNER JOIN categories c ON cm.id_c = c.id_c
WHERE
c.id_c = 2;
EDIT:
#e4c5 link explains why it is bad to store collections like this...
SELECT * FROM my_table WHERE categories LIKE '%2%' AND categories!='1,2,3' AND categories!='2,12';

using where statement with a sequence of ids

In my table, I have a column that it has a set of users id. its name is users_id.
each id separated with a comma(,).
ex : users_id = '1,2,3,4,5';
if I passed $id=1 to my function, how can I using where statement ?
function($id){
$sql = "select * from content_noti
where ??????"
}
You can add a leading and a trailing , in the field value in DB.
e.g.
Change
1,2,3,4,5
to
,1,2,3,4,5,
So that every Id has leading and trailing comma ,
Now, update the function body:
function($id){
$sql = "select * from content_noti
where users_id LIKE '%,$id,%'"
}
In this case you don't have any possibility of mistake as if you search user id 1 then you will get only 1 and not 11 or 111 or 1343.
Working Demo
if you have multiple ids than it would be better to use IN with query
$sql = "select * from content_noti where id IN (?)"
if you are looking for reverse than use find_in_set
$sql = "select * from content_noti where FIND_IN_SET(?, id)";
You can use regular expressions in mysql:
function($id){
$sql = "SELECT * FROM content_noti WHERE users_id REGEXP '(^|,)" . $i . "($|,)'";
}
SELECT * from content_noti where users_id = "1" OR users_id = LIKE '%1,%' OR users_id = LIKE '%,1%'
Storing multiple chunks of data as a single comma seperated colum is really poor design for databases and if at all possible you should look into normalizing this by making a coupling table and joining on that.
The performance of the above query will be terrible and it'll be hard to maintain.

PHP PDO result from query

I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks
group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));
try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.

I want to select record multiple key with like

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

Categories