Home » Php » php – MySQL Filter JSON_CONTAINS Any value from Array

php – MySQL Filter JSON_CONTAINS Any value from Array

Posted by: admin July 12, 2020 Leave a comment


I have a JSON field in a MySQL database that contains values like [1,3,4,7]. I would like to be able to easily supply another array from a PHP variable and determine if there is any overlap. I know this example does not work, but this is what I am trying to do:

$DaysVar = $_GET['Days']; --Example is [1,5,8]

$sql = mysqli_query($db, "
    SELECT ScheduleID, 
           Days --Example is [1,3,4,7]
    FROM Schedule
    WHERE JSON_CONTAINS(Days, '$DaysVar')

How can I get this query to return a result since there is a 1 in each array?

How to&Answers:

You could perform a JSON_CONTAINS for each separate value:

FROM   Schedule 
        OR JSON_CONTAINS(Days, '2')
        OR JSON_CONTAINS(Days, '6')

When the values to be searched for are stored in a PHP variable, then you could build the above SQL like this:

$DaysVar = $_GET['Days'];
$condition = implode(" OR ", array_map(function($day) {
    return "JSON_CONTAINS(Days, '$day')";
}, $DaysVar));
$sql = mysqli_query($db, "
    SELECT ScheduleID, 
    FROM   Schedule
    WHERE  ($condition)