0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.