-2

I am writing a search query for the items in my cart. The problem is I am not getting the expected result. Here is the code:

$here = explode(" ",$sarc);
$query = "SELECT * FROM 126link WHERE (";
foreach($here as $each){
    $i++;
    if($i==1)
        $query.="title LIKE '%$each%') AND loginid = '$myid' ";
    else
        $query.="OR title LIKE '%$each%') AND loginid = '$myid' ";
}
$ritw = mysql_query($query);
$sup = @mysql_num_rows($ritw);
$query.="ORDER BY idl LIMIT 40";
$query = mysql_query($query);
$numrows = @mysql_num_rows($query);

I want to add an AND condition in this query which will search if idcolumn(in table) = '$id' , but I don't know where to put it.

The code above displays results for all carts, I'm trying to limit it to one.

Prashant
  • 37
  • 4

4 Answers4

1

You need to understand the order of operations better:

http://dev.mysql.com/doc/refman/5.5/en/operator-precedence.html

AND is evaluated before OR so without providing parenthesis around your entire set of OR conditions, you will end up evaluating only the last LIKE condition together with the id filter, and then get all teh other rows meeting your OR conditions.

Even without regard to operator precedence, it is a good practice to make logical groupings of your operations to where they make more sense to someone (including yourself) trying to read the code.

So you WHERE condition should look like this:

WHERE (title LIKE %value% OR title LIKE %other value% ...) AND loginid = ?
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • You don't want the `AND loginid` part within your loop. Just have it after the loop like you did before and just close the parenthesis there like `") AND loginid = '$myid'"` – Mike Brant Jan 24 '13 at 23:57
0

Add it at the end?

$id=$_SESSION['id'];
$query = "SELECT * FROM table WHERE ";
foreach($here as $each){
    $i++;
    if($i==1)
        $query.="title LIKE '%$each%' ";
    else
        $query.="OR title LIKE '%$each%' ;
}
$query .= " AND something IN ($id)";

You need to provide a table structure with sample data and a desired result if you want a better answer.

Kermit
  • 33,827
  • 13
  • 85
  • 121
0

Faster way of doing this:

$here = explode(" ",$sarc);
$id=$_SESSION['id'];
$query  = "SELECT * FROM table WHERE title REGEXP '" . implode('|',$here) . "'";
$query .= " AND something IN ($id)";

Have another question about this

Mysql Like multiple values

Community
  • 1
  • 1
Ragen Dazs
  • 2,115
  • 3
  • 28
  • 56
0

This code should work .

$here = explode(" ",$sarc);
$query = "SELECT * FROM 126link WHERE loginid = '$myid'  AND title '".implode('|',$here)."';" ;

$ritw = mysql_query($query);
$sup = @mysql_num_rows($ritw);
$query.="ORDER BY idl LIMIT 40";
$query = mysql_query($query);
$numrows = @mysql_num_rows($query);

To learn REGEXP visit http://www.go4expert.com/forums/showthread.php?t=2337

To learn reqular expressions visit http://www.regular-expressions.info/

Arif
  • 978
  • 12
  • 29