Question

I have session stored with value (not array, just text) : '1, 2'.

$_SESSION['locs'] = '1, 2';

And i have mysql table called (operators) with this fields:

op_id, op_name, location

1 sami 1, 3, 5

2 foo 1

3 boo 4, 5

I want to get results where any number in location is exist in session value.

I tried with WHERE IN statements but I don't know how to take each number session or location.

Can any body help me.

Sami

Was it helpful?

Solution 2

You may explode your session value to array:

$locs = explode(', ' $_SESSION['locs']);

And SQL was follow:

$where = "WHERE ";
$count = count($locs);
for ($i = 0; $i < $count; $i++) {
    $where .= "location LIKE '%, ". $locs[$i] .",%' ";
    $where .= " OR location LIKE '%, ". $locs[$i] ."%' ";
    if ($i < $count - 1) {
        $where .= " OR ";
    }
}

Or use MySQL RegEx for regular expression search

Better way is to use REGEXP:

$where = "WHERE ";
$count = count($locs);
for ($i = 0; $i < $count; $i++) {
    $where .= "location REGEXP '(,[[:blank:]]*|^)". $locs[$i] ."(,|$)'";
    if ($i < $count - 1) {
        $where .= " OR ";
    }
}

I tested them, it's work on "1, 2, 3" string for any number.

OTHER TIPS

Here's your query, using regular expressions. You'll need to figure out to generate it in PHP:

SELECT * FROM operators
WHERE location REGEXP '[[:<:]]1[[:>:]]'
OR location REGEXP '[[:<:]]2[[:>:]]'

Unfortunately, this will scan all records in the operators table.

Consider using an intersection table instead by normalizing the locations into a separate table like this:

table: operators
op_id  op_name
--------------------------
1      sami
2      foo
3      boo

table: operator_locations
op_id   location
---------------------------
1       1
1       3
1       5
2       1
3       4
3       5

And use joins instead of regular expressions.

SELECT o.*
FROM operator_locations ol
JOIN operators o
ON o.op_id = ol.op_id
WHERE ol.location = 1
OR ol.location = 2

This will allow the query to use indexes. Besides performance, the savings aren't obvious here, but when you run out of room in your locations column or want to do something more complex like aggregates, you'll see the benefit.

Based on comments from Victor's answer, correct SQL was follow:

$where = "WHERE ";
$count = count($locs);
for ($i = 0; $i < $count; $i++) {
    $where .= "location = '". $locs[$i] ."' ";
    $where .= " OR location LIKE '%". $locs[$i] .",%' ";
    $where .= " OR location LIKE '%, ". $locs[$i] ."%' ";
    if ($i < $count - 1) {
        $where .= " OR ";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top