check if exists in two coma separated values mysqli - php

I am having an issue where I have a table in a database which stores values in this form 1,3,4,55,6,22,44 and I have an array which is dynamic from the client side it can be like 2,55,33,1,33,99
I want to make a query to select this field if the at least any value matches between the fields.
Like select the field if in the database value there exists 24 and I have 23,24,55,66 from the user array
I think this can be done with find_in_set() or the IN keyword

It is not a good practice to create comma seperated values in a column. Usually people feel that it was the easiest and simplest method, but it is not. Searching and modification will be so hard. Find set can be used if you have a single item to search ; In your case you can do it like this. Implode the array with | and use it in regular expression.
<?php
$arr = Array(2,55,33,1,33,99);
echo 'select * from table where CONCAT(",", `field`, ",") REGEXP ",('.implode("|",$arr).'),"';
?>

For comparing two arrays, you should use:
array_intersect()
after converting table data into array as well.
Reference

Related

How to check if a DB array matches any values of a given array

I'm a little bit stuck.
I have an SQL column that contains weather codes (like Rain, Snow, etc.)
It is comma separated so the column would have a value of something like
rain,snow,haze
Now, I want to select the rows that contain values from an array.
I have an SQL code that is something like this:
SELECT * FROM locations WHERE currentWeather IN ('rain', 'snow', 'cloudy') ORDER BY name ASC
The problem is that this obviously works when currentWeather column only contains one item.
Is there a way to do it so that if the column value contains any of the items from the given array, it selects it?
Also, would it select it twice if two items match?
Best wishes
Use unnest in a subselect.
Select distinct A.myArray from (select unnest(column) as myArray from table) A where A.myArray in (your words to filter for)
Notice that using arrays in sql isn't very ideal and does not follows normalization rules. Your tables should ideally not contain arrays but rather just several rows each one containing the specific value you Want. It prevents issues such as this one.
To avoid the selection of repeated values, use the Distinct keyword right after you write select.
Rsference:
https://www.w3resource.com/PostgreSQL/postgresql_unnest-function.php
WHERE FIND_IN_SET(currentWeather, "rain,snow,cloudy")
Picks apart the string at commas (only) to see if currentWeather is any one of those 3 'words'.
See also FIELD(...)

How to extract one value from imploded array in MySQL row

I'm using implode to insert few values into one row in MySQL database.
implode(' ', $_POST['tag']);
Assuming that I have table named product with row named tags with 3 different values that inserted inside like this:
usb adapter charger
I have tried using this method using like operator (%), but that didn't worked.
$sql = "SELECT * FROM product WHERE tags='%usb%'";
How can I extract only one value from the imploded array using WHERE in mysql query?
I agree with the comments about re-designing the database. At first read it seems that using LIKE would definitely get the result you want but after reading #Patrick Q's pan - panther example, it makes a lot sense that LIKE is not really a good solution. There are ways to get exactly the tag string you're looking for but it may hurt the performance and the query will be longer and complex. Hence the following are to demonstrate how the query would look like with your current tags data value:
MySQL query:
SELECT tags,
SUBSTRING_INDEX(SUBSTRING_INDEX(tags,' ',FIND_IN_SET('usb',REPLACE(tags,' ',','))),' ',-1) v
FROM mytable
HAVING v = 'usb';
As you can see, there are a few functions being used just to get the exact string from the data cell. Since your example data was separating with spaces and FIND_IN_SET identify value separation by comma, REPLACE take place on the tags column first to replace spaces with comma. Then with SUBSTRING_INDEX twice to get the string using the location extracted in FIND_IN_SET. Finally at the end HAVING to get only the tag you're looking for.
Further demo here : https://www.db-fiddle.com/f/joDa7MNcQL2RakTgBa7qBM/3

search exact string exist within column mysql

I'm using below sql query for search values from db, but when I search 'study' it will returns the values 'caese-study', 'get-study-materials' as well.
How can I use a query to search exact contains withing string column?
$names = 'study';
and the names column has values like comma separated,
Ex: 'study, abc, new' so I need to search within that too
SELECT * FROM datatitle WHERE names LIKE '%$names %' ;
SELECT * FROM datatitle WHERE names regexp '(^|[[:space:]])$names([[:space:]]|$)';
I try with above two queries but didnt work as expect, pls advice?
You should not be storing comma-separated values in a column. You should be using a junction/association table. You should fix the data model, if you can.
However, sometimes we cannot control other people's really bad decisions. MySQL has find_in_set():
SELECT dt.*
FROM datatitle dt
WHERE find_in_set(?, names) > 0;
Note that I have replaced the constant $names with a parameter. You should learn to use parameters to pass values into queries.

How to search for comma separated multiple values

I have created a table in MySQL in which a "skill" field has multiple comma-separated values, for instance: "PHP, JavaScript, C#".
I want to know an SQL query which will go through all values and give back a result according to the search values.
The correct MySQL function is FIND_IN_SET().
You would use it like:
SELECT * FROM USERS WHERE FIND_IN_SET('PHP', skill)>0
Where you can swap PHP out for the string you are searching for. This isn't the most efficient way to organize this data, but for smaller data sets might be fine.

Any Other Faster Execution Method For This MYSQL search query?

I have 100K datas in my mysql database, I want to search a query in it. I removed stop-words and splitted it into an array of keywords and stored in a variable ie $key[0],$key[1],$key[2].I am using the following query
SELECT *
FROM `table`
WHERE (`column` LIKE '%$key1%'
OR `column` LIKE '%$key2%'
OR `column` LIKE '%$key3%');
is any other faster ways to do the same.
The only way to speed up queries like this is to use full-text searching. LIKE '%string%' can't be optimized with normal indexes, because they use B-trees that depend on matching the prefix of the string being searched for. Since your pattern begins with a wildcard, the index doesn't help.
Another solution is to normalize your database. Don't put the keywords all in one column, put them in another table, with a foreign key to this table and a row for each FK+keyword. Then you can use a join to match the keywords.
Also, you're using the wrong type of quotes around your column names. They should be backticks, not single quotes.
you can do something like this
SELECT *
FROM table
WHERE colomn REGEXP '$key1|$key2|$key3'
etc etc so instead of creating your array as a comma separated list of key words do it as a pipe separated list and then just push the string into your regex too this is simply an example
Don't SELECT *, only select what you need.
If you want to do complete-text searches, lose the % and add an index
You misspelled column

Categories