...

View Full Version : help with searching a table



steviecee
06-28-2005, 11:33 AM
I'm writing a web site which will allow the user to search for a item using more than one user input, I'm struggling to get my head round the logic though.

for example if a user inputs four entries into a web form what is the best way to search the mysql database using these four entries? i've been thinking about using a switch statement in php, or using numerous 'ifs' in sql code, any ideas on what would be the best way, or any other ways?

also if any of the web form fields are left empty can you make php / mysql discard these?

any ideas on the best way to tackle this would be great, i've had a look round the web and nothing seems to answer my questions, although i'm sure there will be answers out there, so any links to info would also be great

Cheers
Steve

looka
06-28-2005, 11:44 AM
perhaps

SELECT .... WHERE col1 LIKE (input1) OR col2 LIKE (input2) ...... ?

im not sure whether the szntax of LIKE is correct, check it yourself.

NancyJ
06-28-2005, 11:48 AM
SELECT * FROM tablename WHERE fieldname = $input1 OR fieldname = $input2 OR fieldname = $input3 OR fieldname = $input4



$sql = "SELECT * FROM tablename WHERE";
$firstrun = true;
foreach ($_POST as $key => $val)
{
if($val != "")
{
if ($firstrun == true)
{
$sql .=" $key = '$val' ";
$firstrun = false;
}
else
{
$sql .=" OR $key = '$val' ";
}
}
}


thats if your fieldnames are the same as your forminputs else just replace $key with the fieldname you're searching

assuming your form inputs are the same name as your fieldnames, if you

steviecee
06-28-2005, 11:53 AM
would it be ok to replace the 'or's' in the sql as 'ands'? i can't see that being a problem?
thanks for the help
steve

NancyJ
06-28-2005, 11:55 AM
would it be ok to replace the 'or's' in the sql as 'ands'? i can't see that being a problem?
thanks for the help
steve
Thats no problem

steviecee
06-28-2005, 11:56 AM
thats great, thanks again
steve



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum