Page 1 of 1
PHP Search MSSQL database
Posted: Fri Apr 04, 2008 9:59 am
by laural
Hi, I have a search field on my webpage. When someone enter search terms, I want to be able to separate them so that I can use them in a sql search. For example, if someone types in - neighbor disputes - I want to search sql like this - SELECT *
FROM database WHERE body LIKE '%neighbour%' AND body LIKE '%dispute%'
I do not know how to separate the values that I collect in my php variable - can anyone shed any light on this for me? Thanks
Laura
Re: PHP Search MSSQL database
Posted: Fri Apr 04, 2008 11:00 am
by kryles
WARNING: Not tested
I would use explode to turn it into an array (seperated by space as the delimiter), then use the keyword IN instead of LIKE.
Don't forget to append a ',' to each element created by using explode.
Code: Select all
$strarray = explode(' ', $_POST['thesearchField']);
for($i=0;$i < count($strarray);$i++)
{
$strarray[$i] = "'".$strarray[$i]."',";
}
/* I forget the syntax atm but take off the last comma off in $strarray[count($strarray)-1]
or just use
for($i=0;$i < count($strarray);$i++)
{
if($i == count($strarray)-1)
$strarray[$i] = "'".$strarray[$i]."'";
else
$strarray[$i] = "'".$strarray[$i]."',";
}
*/
$query = "SELECT * FROM database WHERE body IN (";
for($i =0; $i < count($strarray);$i++)
{
$query .= $strarray[$i];
}
$query .= ")
echo $query;
This will find if it has neighbour OR dispute. Not exactly what you asked for but maybe it'll give you an idea
Re: PHP Search MSSQL database
Posted: Fri Apr 04, 2008 11:43 am
by laural
Yes, I have to have an AND, not an OR - I will see what I can do to work with this... but if anyone else out there has an idea that is closer to what I am looking for, I would be very grateful...
Again, thanks for giving me this code to work with, I will post back if I can get it to work
