0

I have a search get variable that can contain multiple words which are space deliminated. I have used the following to script to grab the url variable. Notice for the example I have just used a string for simplicity.

What I have tried to do is explode the variable value and then add on the needed sql before and after.

The echo works fine. It is this echo that I need as a variable in a sql within the code that follows.

My problem is that it just returns the last query metal when I reference it outside within the query as a string. I am so new to this, please any help would appreciated.

<?php

$string = "kitchens wooden metal";
$splitted = explode(" ",$string);
$cnt = count($splitted);
$i=0;
while($cnt > $i)
{
    $sqlsnippet = "cats_sub.cats_sub_ms_desc LIKE %$splitted[$i]%";
    $i++;

    echo $sqlsnippet;
}

?> 
edorian
  • 38,542
  • 15
  • 125
  • 143
user1093405
  • 41
  • 1
  • 2
  • 7

2 Answers2

0

My code:

<?php

$string = "kitchens wooden metal";
$splitted = explode(" ",$string);
$cnt = count($splitted);
$i=0;
while($cnt > $i)
{
$sqlsnippets[] = "cats_sub.cats_sub_ms_desc LIKE '%$splitted[$i]%'";
$i++;

}
$sqlsnippet = "(" . implode(" or ", $sqlsnippets) . ")";

echo $sqlsnippet;
?> 

Result:

(cats_sub.cats_sub_ms_desc LIKE '%kitchens%' or cats_sub.cats_sub_ms_desc LIKE '%wooden%' or cats_sub.cats_sub_ms_desc LIKE '%metal%')

Optimized version:

<?php

$string = "kitchens wooden metal";
$sqlsnippet = "(cats_sub.cats_sub_ms_desc LIKE '%" . preg_replace("/ /", "%' or cats_sub.cats_sub_ms_desc LIKE '%", $string) . "%')";
echo $sqlsnippet;

?> 
deejayy
  • 760
  • 3
  • 9
0
$sqlsnippet = "cats_sub.cats_sub_ms_desc LIKE %$splitted[$i]%";

This overrides $sqlsnippet for every iteration of the while-loop. That's the reason why you only get the last SQL snippet.

You need to concatenate the SQL snippets, like this:

$sqlsnippet = 'WHERE ';

foreach($i = 0; $i < count($splitted); $i++)
{
    // Append AND 
    if($i > 0)
    {
        $sqlsnippet .= ' AND ';
    }

    $sqlsnippet .= 'cats_sub.cats_sub_ms_desc LIKE %' . mysql_real_escape($splitted[$i]) . '%';
}

var_dump($sqlsnippet);
CodeZombie
  • 5,367
  • 3
  • 30
  • 37