1

I want to fetch data from my user table which tag id stored like :

userid  tagid 
5036    |4815|324|                
1396    |1393|4567|                   
2676    |2669|345|2345|

I have a tagid array like as Array ( [0] => 4815 [1] => 4567 )

Need to fetch data using mysql where in condition like "select * from user where tagid in ()". Is there any preg_match function for it?

4
  • 1
    Can you just do where tagid like '%|4815|%' ? Of course that's not efficient but it's the way the table is designed. Commented Jun 11, 2013 at 15:43
  • but the problem is i have array of tagids and to do search with that array. Commented Jun 11, 2013 at 15:45
  • Loop the array and append the values to the where. Commented Jun 11, 2013 at 15:48
  • 1
    The problem is that your tables are not normalized. See stackoverflow.com/questions/3653462/… for why your tagid column is going to cause you sorrow and pain until you create a separate table. Commented Jun 11, 2013 at 15:58

3 Answers 3

1

Suggest you loop the array and append using likes, something like:

   $tags = array(2,4,6);
   $query = 'select * from user where ';
   foreach($tags as $i=>$tag) {
       if ($i>0) $query.=' or ';  // or and?
       $query.='tagid like "%|'.$tag.'|%"';
   }
Sign up to request clarification or add additional context in comments.

1 Comment

This works as long as their own array isn't indexed with something else. Cool concatenation though.
0

Because you're having to use a wildcard on both sides of the match they would both be about the same (I think regexp may be a little faster in your case).

The problem is that you may have false positives because of the chance of a substring in your searches because of the lack of normalization.

An example:

Searching for %15%

Matches 915,15,150,215790

Because of this, you should actually do this, since in this case, LIKE would not be sufficient unless you always wrap the IDs in the pipe characters |:

<?php
    $ids = array('115','215','225');

    foreach($ids as $id){

      $query = "select * from user where tagid regexp '[^0-9]*$id[^0-9]*'";

    }

?>

At which point you could use this:

<?php
    $ids = array('115','215','225');

    foreach($ids as $id){

      $query = "select * from user where tagid like '%|$id|%'";

    }

?>

1 Comment

@CasimiretHippolyte as long as they stick to their non-standard convention of surrounding the IDs with pipe characters.
0

You can do it like that:

$tagid = array(4815,4567);
$query = "select * from user where tagid regexp '\|("
       . implode("|", $tagid) . ")\|'";

then you obtain:

select * from user where tagid regexp '\|(4812|4567)\|'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.