如何在 WHERE 中为 LIKE 和 % 使用准备好的语句?
How to use prepared statement for LIKE and % in WHERE?
我目前正在构建准备好的语句,我想知道如何在 LIKE 和 % 的 WHERE 部分中使用它。所以我基本上只想 SELECT 数据库中的名称,就像已发布的名称一样。
这是我的代码:
$order = "SELECT name, name_id FROM requests WHERE name LIKE %?%" ;
$statement = $pdo->prepare($order);
$statement->bindParam(1, $_POST['name']);
$statement->execute();
$data = $statement->fetch(PDO::FETCH_ASSOC);
这是一个奇妙的错误,说我对 %:
使用了错误的语法
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
to use near '%'kevin'%' at line 1' in
/var/www/xxx/html/partials/requestinsert.php:13 Stack trace: #0
/var/www/xxx/html/partials/requestinsert.php(13): PDOStatement->execute() #1
/var/www/xxx/html/partials/requestcontact.php(231):
include('/var/www/xxx...') #2 /var/www/xxx/html/xxx.php(124):
include('/var/www/xxx...') #3 {main} thrown in
/var/www/xxx/html/partials/requestinsert.php on line 13
绑定如下参数时需要提供查询参数:
$order = "SELECT name, name_id FROM requests WHERE name LIKE ?" ;
$var = "%" . $_POST['name'] . "%";
$statement->bindParam(1, $var);
我目前正在构建准备好的语句,我想知道如何在 LIKE 和 % 的 WHERE 部分中使用它。所以我基本上只想 SELECT 数据库中的名称,就像已发布的名称一样。
这是我的代码:
$order = "SELECT name, name_id FROM requests WHERE name LIKE %?%" ;
$statement = $pdo->prepare($order);
$statement->bindParam(1, $_POST['name']);
$statement->execute();
$data = $statement->fetch(PDO::FETCH_ASSOC);
这是一个奇妙的错误,说我对 %:
使用了错误的语法Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
to use near '%'kevin'%' at line 1' in
/var/www/xxx/html/partials/requestinsert.php:13 Stack trace: #0
/var/www/xxx/html/partials/requestinsert.php(13): PDOStatement->execute() #1
/var/www/xxx/html/partials/requestcontact.php(231):
include('/var/www/xxx...') #2 /var/www/xxx/html/xxx.php(124):
include('/var/www/xxx...') #3 {main} thrown in
/var/www/xxx/html/partials/requestinsert.php on line 13
绑定如下参数时需要提供查询参数:
$order = "SELECT name, name_id FROM requests WHERE name LIKE ?" ;
$var = "%" . $_POST['name'] . "%";
$statement->bindParam(1, $var);