I have done some looking but to be honest I just dont know what exactly to search. What I am trying to do is create a dynamic query as the tittle says. That is, one where I query only the variables that are sent to the php file. For example if I want to look up users but I only know their last name and username however for another user I know his firstname and email. I want to give the search form many fields and create a query based on what fields were entered.
1 Answer
Build up a list of WHERE clauses first and then add these into your query. For example:
$where = "";
if (isset($firstname) {
$firstname = mysql_real_escape_string($firstname);
$where .= "AND firstname='$firstname'";
}
if (isset($lastname) {
$firstname = mysql_real_escape_string($lastname);
$where .= "AND lastname='$lastname'";
}
mysql_query("SELECT * FROM users WHERE 1 ".$whereClause);
Of course you will need to change the table/row/etc names and add extra if (isset sections for each attribute.