[英]Is there a wildcard operator for the MySql WHERE clause?
The following MySql SELECT via PHP successfully returns rows containing a color specified by the variable $my_color
. 以下通过PHP进行的MySql SELECT成功返回包含由变量$my_color
指定的颜色的行。
$my_color = "red";
$a = $pdo->prepare("SELECT * FROM my_table WHERE color=:color");
$a->bindParam('color', $my_color);
$a->execute();
$data = fetchAll(PDO::FETCH_ASSOC);
I would also like to perform searches that are not dependent on specific colors. 我还想执行不依赖于特定颜色的搜索。 I can do this with an if-then block to use a different SELECT pattern but... 我可以使用if-then块来执行此操作,以使用不同的SELECT模式,但是...
Question: Does MySQL have the ability to set a WHERE condition to something that translates to "accept anything" ( WHERE = *
)? 问题: MySQL是否有能力将WHERE条件设置为转换为“接受任何东西”的内容( WHERE = *
)?
You can use a LIKE clause with the input being a wildcard character like this: 您可以使用LIKE子句,并且输入是通配符,如下所示:
$my_color = "%";
$a = $pdo->prepare("SELECT * FROM my_table WHERE color LIKE :color");
$a->bindParam('color', $my_color);
$a->execute();
$data = fetchAll(PDO::FETCH_ASSOC);
Use LIKE
instead of =
. 使用LIKE
代替=
。 If the value doesn't contain any wildcard characters, LIKE
performs an exact equivalence check. 如果该值不包含任何通配符,则LIKE
执行精确的等效性检查。 But then you can use %
as a wildcard to match anything. 但是随后您可以将%
用作通配符以匹配任何内容。 So: 所以:
$color = '%';
$a = $pdo->prepare("SELECT * FROM my_table WHERE color LIKE :color");
$a->bindParam('color', $my_color);
$a->execute();
$data = fetchAll(PDO::FETCH_ASSOC);
However, a better option might be to put the logic in PHP rather than SQL. 但是,更好的选择可能是将逻辑放在PHP中而不是SQL中。
if ($color) {
$a = $pdo->prepare("SELECT * FROM my_table WHERE color=:color");
$a->bindParam('color', $my_color);
} else {
$a = $pdo->prepare("SELECT * FROM my_table");
}
$a->execute();
See https://stackoverflow.com/a/28909923/1491895 for a more general technique for building the WHERE
clause dynamically from multiple form inputs. 请参阅https://stackoverflow.com/a/28909923/1491895 ,以了解从多种表单输入动态构建WHERE
子句的更通用技术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.