简体   繁体   English

如果还有 2 或 3 个帖子,我如何过滤 PHP 帖子并添加“和”?

[英]How can i filter PHP posts and add 'and' if 2 or 3 more posts exists?

I want to make a php code , so when the user wants to filter he checks the options for example ,specialism , location and gender .我想制作一个 php 代码,所以当用户想要过滤时,他会检查选项,例如专业、位置和性别。 If he checks only for specialism the query should be:如果他只检查专长,则查询应该是:

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

And if user checks specialsim and location :如果用户检查 specialsim 和 location :

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

and so on.等等。 I want all this code to be in on function.我希望所有这些代码都能发挥作用。

First of all, you are introducing an SQL injection , you may want to use a parameterized statement in order to avoid this.首先,您正在引入SQL 注入,您可能希望使用参数化语句来避免这种情况。

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也就是说,这种查询的一个常见技巧是添加一个始终为真的子句(通常为11 = 1 ),以获得类似

"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.所以你基本上总是在你的查询中添加一个AND

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM