Forum Moderators: coopster

Message Too Old, No Replies

Multiple queries to a MySQL DB

Optimize the code

         

SuMajestad

4:24 pm on Jul 20, 2004 (gmt 0)

10+ Year Member



--Sorry for my english!----

Here is my problem:

I have a HTML form that has the following inputs:
First Name
Last Name
Age
Gender
City of residence
Job
and more fields..

The form is for showing the records from the DB that match with the info that was captured, for example, if the user want to view the people named "Steve" and lives in LA and the user leaved all the other fields empty.
One way to do that is writing all the possible combinations, but that will be a lot of code (and If´s), so I wanted to ask if there is a better way to do that?

I thought about making the string for the query only with the fields captured, but I have problems with the '' and the "".

Again, sorry if I am not very clear

SuMajestad
Mexico

coopster

6:27 pm on Jul 20, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, SuMajestad!

I think I understand you correctly. Would something like this give you an idea for a start?

$where_statement = "WHERE 1=1"; 
if (isset($_POST['firstname']) {
$where_statement .= " AND firstname LIKE '" . $_POST['firstname'] . "'";
}

SuMajestad

11:15 pm on Jul 20, 2004 (gmt 0)

10+ Year Member



Thanks, coopster!

Well, just after I posted the message, I wrote a very similar code to yours:

$flag=0;
$sql_query='select * from data where ';
$n=$_POST['txtname'];
if ($n<>'')
{
if ($flag==0)
{
$sql_query=$sql_query."name='".$n."' ";
$flag=1;
}
else
{
$sql_query=$sql_query."and name='".$n."' ";
}
}
//The same for all the rest of the fields..

I will add the validation you wrote in your code, coopster.

It works fine!

Again, thanks for your time

SuMajestad
La Paz, Mexico