2015-12-19 62 views
1

我目前正在构建准备好的语句,我想知道如何在LIKE和%的WHERE部分中使用它。所以我基本上只想从数据库中选择名称,就像已发布的名称。如何在LIKE和%WHERE中使用预备语句?

这里是我的代码:

$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 

回答

1

你需要的时候,你绑定提供查询参数参数如下:

$order = "SELECT name, name_id FROM requests WHERE name LIKE ?" ; 
$var = "%" . $_POST['name'] . "%"; 
$statement->bindParam(1, $var); 
+0

噢好吧,谢谢! – Franky2207