1

I'm new to php and i don't have the formal study, since i study it myself i have a problem and i hope someone can help me.. :(

I have and array

$array = array("where","are","you" and so on.....);

and i want to search the database with all those values

like

$sql_res1 =mysql_query("select * from lady_vega where react like '%$array[0]%'");  
$sql_res2 =mysql_query("select * from lady_vega where react like '%$array[1]%'");  
$sql_res3 =mysql_query("select * from lady_vega where react like '%$array[2]%'"); 

.... and so on

there are times that the array don't have the exact number of values.

and someone said to me that loop could be a help...
but i don't know how...

and i also want the results of each mysql query will be stored like this so that i can i dentify which results are from...

$row1  = mysql_fetch_array($sql_res1);  
$row2  = mysql_fetch_array($sql_res2);  
$row3  = mysql_fetch_array($sql_res3);  

... so on

i hope there would a possible solution/technique to this..

Julian Paolo Dayag
  • 3,562
  • 3
  • 20
  • 32

3 Answers3

2

Try using the following:

$sql = "select * from lady_vega where react like '%".implode("%' OR react LIKE '%", $array)."%'"
$sql_res1 =mysql_query($sql);

You can chain multiple where clauses using OR and AND in your query:

WHERE field = 'value' AND field2 = 'value'

Ben Rowe
  • 28,406
  • 6
  • 55
  • 75
  • 1
    This is the correct answer, but I'd suggest that perhaps you are looking for an "IN" query rather than "react like...". Ultimately you want WHERE clause to read something like this: " WHERE react IN ("where","are","you", "and so on.....");" – jn29098 Apr 02 '12 at 01:53
  • 1
    IN won't help here if he really wants to do a LIKE comparison. This will work fine, or you can build a regexp and it will probably be more efficient if you have a high number of OR statements being built. Check here for how it works: http://stackoverflow.com/questions/1127088/mysql-like-in – Brad Harris Apr 02 '12 at 01:59
  • What is the output you were expecting? let us know so we can better answer you – iWantSimpleLife Apr 02 '12 at 04:58
0

You could try using a foreach loop for example.

$terms = explode(",",$array);

$query = "select * from lady_vega where ";

foreach($terms as $each){
    $i++;
    if($i ==1){
    $query.="react LIKE '%$each%'";

    }
    else
        $query .= "OR react LIKE '%$each%' ";


    }
0
$sql = "";
for($i=0;$i<count($array);$i++){
    $sql.="select *,'".$array[$i]."' as keyword from lady_vega where react like '%".$array[$i]."%'";  
    if($i!=count($array)-1) $sql .= " union ";    
}

$result = mysql_fetch_array(mysql_query($sql));

$last_keyword="";
$index = 1;
foreach($result as $row){
    if($last_keyword!=$row["keyword"]){ 
        $index++;
        ${"row".$index} = array();
    }
    array_push(${"row".$index},$row);
}

then you'll get the same result with an extra "keyword" column.

Taha Paksu
  • 15,371
  • 2
  • 44
  • 78