Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parsing a user entered search string

Status
Not open for further replies.

HobbyMan

Programmer
Sep 22, 2000
25
0
0
US
What I want to do is take a string,
entered by the user, and then make
a valid database query from that.

They will be searching a text field for
certain words. What I am having a
problem with is taking the input and
creating the query.

If they type in:
CDE -sun -solaris

I want to have this query string:
where contains (problemdesc, ' "CDE" AND NOT "sun" AND NOT "solaris" ')

How do I get the resulting query string?
 
the hard part is you have no way to separate the user inputs out without potentially causing a problem

$request=$_POST['crtieria'] //from text box name criteria

$search_array=split(" ",$request); [red]/*split on spaces which will cause trouble if the user uses a space in a phrase*/[/red]

$element_count=count($search_array);

if ($element_count==1){
$sql="select * from mytable where problemdesc like '%$search_array[0]%'"; //only one criteria
}else{
$sql= "select * from mytable where problemdesc like ";
for ($x=0;$x<$element_count;$x++){
if ($x==0){
$sql.=&quot;'%&quot;.$search_array[0].&quot;%'&quot;;
}else{
$sql.=&quot; AND '%&quot;.$seach_array[$x].&quot;%'&quot;;
}
}
$sql=str_replace(&quot;-&quot;,&quot;NOT&quot;, $sql); //replace the minus sign with the NOT operator
//echo the query to see if correct
echo $sql;
//execute the query
$result=mysql_query($sql);


hth Bastien

There are many ways to skin this cat,
but it still tastes like chicken
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top