Home > Mobile >  How can i filter PHP posts and add 'and' if 2 or 3 more posts exists?
How can i filter PHP posts and add 'and' if 2 or 3 more posts exists?

Time:11-10

I want to make a php code , so when the user wants to filter he checks the options for example ,specialism , location and gender . If he checks only for specialism the query should be:

"SELECT * FROM users WHERE specialsim = $specialsim";

And if user checks specialsim and location :

"SELECT * FROM users WHERE specialism = $specialism AND location = $location;

and so on. I want all this code to be in on function.

CodePudding user response:

First of all, you are introducing an SQL injection, you may want to use a parameterized statement in order to avoid this.

That said, a common tip for this kind of query is to add an always true clause (often 1 or 1 = 1), to get something like

"SELECT * FROM users WHERE 1 AND specialism = $specialism";

If you have multiple clause you can then write it like:

$query = "SELECT * FROM users WHERE 1";
if ($specialsim !== null) $query .= " AND specialism = $specialism";
if ($location !== null) $query .= " AND location = $location";
if ($gender !== null) $query .= " AND gender = $gender";

So you just basically always add a AND to your query.

  • Related