Web Hosting Talk







View Full Version : MySQL query build up


WebGuru72
10-13-2006, 11:25 PM
Here is something challenging for me.... I have been thinking about it but never had to do it and it come.
I will have a few drop downs selections, the user can select the ones he\she wants (these are basically conditions the user selects to do a search)
Once those selections are made, how can I feed them into the query, some can be left blank and some are selected. I hope I am clear

arkin
10-14-2006, 12:23 AM
Assuming you know how to use MySQL queries,
something along these lines would help you:
if (!empty($_POST['option1'])) $query.=" AND `option1` = '{$_POST['option1']}'";

If you require any more assistance, please elaborate a little more.

WebGuru72
10-14-2006, 12:29 AM
Ok this is very good. now what if the first one is blank. then when they get to optio1 (assuming it is the second option) it would read select AND 'option1 from table
do you know what I mean

arkin
10-14-2006, 12:34 AM
Basically, you have 3 fields - option1, option2 and option3.

With my method:
$query="SELECT * FROM `table` WHERE `type` = 'news'";
if (!empty($_POST['option1'])) $query.=" AND `option1` = '{$_POST['option1']}'";
if (!empty($_POST['option2'])) $query.=" AND `option1` = '{$_POST['option2']}'";
if (!empty($_POST['option3'])) $query.=" AND `option1` = '{$_POST['option3']}'";

You have to have that initial WHERE event, to prevent what you were saying.

WebGuru72
10-14-2006, 01:34 AM
Ok makes sense..... Last question, how would you do the quotes.... see now
`type`= 'news'" here you closed the quotes... would that not matter since you are appending to the query? Sorry I am not thinking.

arkin
10-14-2006, 01:56 AM
No, the quotes tell PHP that its a string, imagine:

"this string is not valid PHP syntax;

Because your not ending the quotes.

http://us2.php.net/manual/en/language.operators.string.php

PHP Online manual is one of the best by far.