I'm trying to get a rather simple search function working but I'm having a bit of trouble. Basically I have a simple form with one text field. The input is then passed as a POST variable, exploded into an array and then checked for any included operators (+/-). I would like to then construct SQL queries based on the input, e.g.,:
I've been able to construct and echo the queries ok as strings (using for loops and substr functons) but I don't know how to construct a single query that depends on a loop. It seems like the for() loop needs to be smack in the middle of the query, or i need to 'echo' the query somewhere as a single variable? Any ideas? Thanks.
edit: Just to clarify, the following code I cleaned up very quickly, so there may be syntax or minor errors....It's really the construction of the actual SQL query from the array/for() I'm having trouble with.
Code:
mac iphone leopard => SELECT * FROM * WHERE * LIKE '%mac%' OR * LIKE '%iphone%' OR * LIKE '%leopard%'
mac +iphone -leopard =>SELECT * FROM * WHERE * LIKE '%mac%' AND * LIKE '%iphone%' NOT * LIKE '%leopard%'
I've been able to construct and echo the queries ok as strings (using for loops and substr functons) but I don't know how to construct a single query that depends on a loop. It seems like the for() loop needs to be smack in the middle of the query, or i need to 'echo' the query somewhere as a single variable? Any ideas? Thanks.
edit: Just to clarify, the following code I cleaned up very quickly, so there may be syntax or minor errors....It's really the construction of the actual SQL query from the array/for() I'm having trouble with.
Code:
$search = $_POST['search']; //variable from form
$searchArr = explode(' ' , $search); //delimit to array using 'space'
$searchCount = count($searchArr); //count number of search terms
//Connect to database(assume I know how to do this)
//Create query and echo output
$i = 0;
if ($i==0) {
$queryPrefix = "mysql_query('SELECT `name` FROM `sfx_song` WHERE `name` LIKE '%" . $searchArr[$i] . "%'";
}
for ($i=1; $i < $searchCount; $i++) {
if (substr($searchArr[$i], 0, 1) == "+") {
echo " AND " . substr($searchArr[$i], 1);
}
else if (substr($searchArr[$i], 0, 1) == "-") {
echo " NOT " . substr($searchArr[$i], 1);
}
else {
echo " OR " . $searchArr[$i];
}
}
$query = mysql_query(); //Assume I know what to do once I get a working query