Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在准备好的语句中使用LIKE_Mysql_Sql_Pdo - Fatal编程技术网

Mysql 在准备好的语句中使用LIKE

Mysql 在准备好的语句中使用LIKE,mysql,sql,pdo,Mysql,Sql,Pdo,我想执行一条语句,以确定包含字符串的列是否包含某个值 +----+------+ | id | st | +----+------+ | 0 | 2183 | | 1 | 5820 | | 2 | 2984 | | ...| ... | +----+------+ 假设我希望找到st包含1的所有行,我将使用以下where条件: WHERE st LIKE "%1%" OR st LIKE "1%" OR st LIKE "1" OR st LIKE "%1" 但我如何在事先准备好

我想执行一条语句,以确定包含字符串的列是否包含某个值

+----+------+
| id |  st  |
+----+------+
|  0 | 2183 |
|  1 | 5820 |
|  2 | 2984 |
| ...|  ... |
+----+------+
假设我希望找到
st
包含1的所有行,我将使用以下where条件:

WHERE st LIKE "%1%"
OR st LIKE "1%"
OR st LIKE "1"
OR st LIKE "%1"
但我如何在事先准备好的声明中做到这一点

$ps = $db->prepare("
    SELECT id
        FROM table
        WHERE st LIKE "%:a%"
        OR st LIKE ":a%"
        OR st LIKE ":a"
        OR st LIKE "%:a"
");
$ps->execute(array(
    ':a' => $var
));

这显然不起作用。

符号
%
必须是
$var
的一部分,而不是准备好的语句的一部分。另外,您只需要
%:a%
它包括where子句的所有其他部分

$ps = $db->prepare("
    SELECT id
        FROM table
        WHERE st LIKE :a
");
$ps->execute(array(
    ':a' => "%".$var."%"
));
试试上面的代码。 还有一件事,如果您需要的行中包含
1
,那么就不需要类似4的条件,您只能使用
'%1%'
来实现


希望这会有所帮助。

符号
%
必须是
$var
的一部分,而不是准备好的语句的一部分。而且你只需要。“%:a%”它包括您的where clauseDo的所有其他部分,而不仅仅是添加代码。解释你做了什么以及为什么。
ps = $db->prepare("
    SELECT id
        FROM table
        WHERE st LIKE :a");
$ps->execute(array(
    ':a' => "%".$var."%"
));