I am currently constructing prepared statements and I am wondering how to use it in the WHERE part for LIKE and %. So I basically just want to SELECT the name from the database which is like the one that has been posted.
Here is my code:
$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);
And here is the wonderful error that says that I use the wrong syntax with %:
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
You need to supply query parameter when you bind the parameters like below:
$order = "SELECT name, name_id FROM requests WHERE name LIKE ?" ;
$var = "%" . $_POST['name'] . "%";
$statement->bindParam(1, $var);