Oliver Giess Oliver Giess - 1 year ago 58
PHP Question

PDO Object: Invalid parameter number: number of bound variables does not match number of tokens

$queryString = 'SELECT * FROM n8593370.items AND Suburb = :suburb AND Name LIKE \'%:name%\'';

$stmt = $pdo->prepare($queryString);
$stmt->bindValue(':suburb', $suburb);
$stmt->bindValue(':name', $name);

$results = $stmt->fetchAll();

I am getting the above mentioned error can not for the life of my figure out why.

I am certain I only have 2 variables to bind and that I indeed bind both.

When I perform this with each conditional on their own i.e.
WHERE 1 = 1 AND Suburb = :suburb
WHERE 1 = 1 AND Name LIKE \'%:name%\'
I do not have any errors.

ALTHOUGH the latter of the two conditionals does not return any results, however when I test it in MySQL Workbench it works as I expect it.

Can anybody shed some light on the issue?

Answer Source

When using placeholder values it's important to leave any and all escaping out of the query. The value itself should be bare, PDO will take care of the escaping for you if you're disciplined about using placeholder values.

Specify it this way:

"...name LIKE :name..."

Then you bind this way:

$stmt->bindValue(':name', "%$name%");