php - SQL Select columns with comparison
610
I have a SQL table which have a column namedkeywords
.
Table:
| id | keywords |
| 0 | music programming guitar |
Now i have an array like|$array = array("boat", "water", "music");
.
My target is to select all columns which have at least one of the things from the array in thekeywords
.
Sql-Query:
"SELECT * FROM table WHERE keywords IN ('".$array."')";
It returns nothing.
Answer
Solution:
The approach I am going to describe is highly not recommended. The correct approach is to have a separate table with one row per
id
andkeyword
. This is a junction table, and it would have rows like:This is the right way to store lists in a relational database. Databases have this great data structure for lists. It is called a table, not a string.
But, if you are really stuck with this situation, then you can hack your way to a solution. Presumably, performance is not an issue.
The hack is to format your list as a regular expression, and create the
where
clause as: