0

This is really a dumb question from a beginner, I have a table called "stations" inside my database and on it I have a column called "keywords". I need to retrieve all those rows that contain one specific keyword (let's say "pizza"). I tried with this but it didn't work:

foreach ($stations->result() as $row) 
{       
    foreach ($row->keywords as 'pizza') 
    {  

        <--my code-->
    }
}

How could I retrieve all rows that contain "pizza" inside a specific column using PHP?

Mureinik
  • 277,661
  • 50
  • 283
  • 320
NineCattoRules
  • 1,848
  • 5
  • 32
  • 75

2 Answers2

2

Instead of parsing it in PHP, you can select only the relevant rows using find_in_set:

SELECT *
FROM   stations
WHERE  FIND_IN_SET ('pizza', keywords) > 0
Mureinik
  • 277,661
  • 50
  • 283
  • 320
2

You can accomplish this using explode() to turn the list into an array. Then you can use in_array():

foreach ($stations->result() as $row) {               
   if ( in_array('pizza', explode(",", $row->keywords) ) ) {
       <--my code-->
   }
}

explode(",", $row->keywords) turns your comma-separated list into an array.

in_array('pizza', $array ) returns TRUE if pizza is found, otherwise it returns FALSE.

Digital Chris
  • 6,129
  • 1
  • 17
  • 29