PHP Search MSSQL database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
laural
Forum Newbie
Posts: 6
Joined: Fri Apr 04, 2008 9:44 am

PHP Search MSSQL database

Post 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
kryles
Forum Contributor
Posts: 114
Joined: Fri Feb 01, 2008 7:52 am

Re: PHP Search MSSQL database

Post 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
laural
Forum Newbie
Posts: 6
Joined: Fri Apr 04, 2008 9:44 am

Re: PHP Search MSSQL database

Post 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 :)
Post Reply