Prepared select statement

I have following PHP code yet cant find what I am doing wrong. Error logs is not really giving me much to go for…

  $myPDO = new PDO('mysql:host=localhost;dbname=myname', $user, $pass); /* Establish new connection, get the PDO object.  */

$stmt = $myPDO->prepare("SELECT * FROM TABLE WHERE name like '%:name%' AND age =':age'");
$stmt->execute(['name' => $s, 'age' => $r]); 
$user = $stmt->fetchAll();

if (sizeof($user) > 0) {
else { 
        error_log("Not so great");

Can anyone suggest how would I go about at least getting some error messages out to find out whats wrong.
As of right now all I see in my log is …

Not so great

Found that when using LIKE special consideration needs to be taken as per below which was found here → Prepared statements and LIKE clause

1 Like

In prepared statements you don’t use quotes around the variables and you will need to add your percent signs outside of the statement. Not tested but something like:

$stmt = $myPDO->prepare("SELECT * FROM TABLE WHERE name like :name AND age = :age");
$stmt->execute(['name' => '%' . $name . '%', 'age' => $age]);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.