Search code examples
phpmysqlsqlexplodeimplode

MySQL PHP select where "X,Y" is in X,Y,Z


How do I complete this code below? I am trying to select news from the database and the locations which can be 23,22,88,90 location codes. I know you can just do IN('23', '22', '88', '90') but the problem is, my locations are a string so it comes out like IN('23,22,88,90') I believe.

How do I expand on the string of locations and select all or any including the locations in the string? So in the database, newsLocations could be 22 23 22,90 23,80,90 90. If that makes sense? so if $locationstoGet has 22,88,90 only, it will get the newsLocation even if the result is just 88,90 without the 22.

$locationsToGet = '22,88';
$db->query("SELECT * FROM news WHERE newsLocation IN($locationstoGet)");

I hope I explained this alright.


Solution

  • I saw a response on another site here

    So I will adapt the solution there to your scenario. Change locationsToGet into an array, and use the implode function to generate the right syntax for the IN Clause.

    $locationsToGetArr = array('22','88');
    $locations = "'".implode("','",$locationsToGetArr)."'"; //this should output '22','88'
    $db->query("SELECT * FROM news WHERE newsLocation IN($locations)");
    

    This solution is assuming your database structure is as such

    +--------+--------------+
    |  news  | newsLocation | 
    +--------+--------------+
    |   1    | 88           | 
    |   1    | 22           |
    |   2    | 22           |
    |   2    | 88           |
    +--------+--------------+
    

    But if you are storing your data as the following instead

        +--------+--------------+
        |  news  | newsLocation | 
        +--------+--------------+
        |   1    | 88,22        | 
        |   2    | 22,88        |
        +--------+--------------+
    

    You will not have much choice besides to select all from news table and have PHP filter the location. Not a very efficient method.