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.

911

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 perid andkeyword. This is a junction table, and it would have rows like:

id       keyword
1        music
1        programming
1        guitar

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 thewhere clause as:

where keywords regexp 'boat|water|music'

People are also looking for solutions to the problem: How to upgrade protocol of client side php websocket. I am using phpWebSocket

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.