Executing a prepared PDO statement with the like clause

sandiegotowy

New Member
I am new to PHP, and am trying to learn to use PDO to connect to a test MySQL db. I have the following:\[code\]try { $db = new PDO('mysql:dbname=MYDBNAME;host=MYHOST', 'USERNAME', 'PASSWORD'); $query = "select * from books where ? like '%?%'"; $stmt = $db->prepare($query); $stmt->execute(array($searchtype, $searchterm)); } catch(PDOException $e) { echo 'PDOException: ' . $e->getMessage();}\[/code\]When I try it I get the following warning:Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokensWhen I remove the like clause, and the $searchterm param, it returns the result properly. I thought -- like '%?%' -- might not be a legal way to create this query under double quotes, so I tried escaping ', which did not work. I looked around for a solution, and found that someone moved '% and %' down to where $searchterm is:\[code\]$query = "select * from books where ? like ?";...$stmt->execute(array($searchtype, '\'%'.$searchterm.'%\'')); \[/code\]I got the same result.
Any help is appreciated. Thanks!/ UPDATE ****/I found on example 12 of http://us3.php.net/manual/en/pdo.prepared-statements.phpExample #12 Invalid use of placeholder\[code\]<?php$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");$stmt->execute(array($_GET['name']));// Below is What they suggest is the correct way.// placeholder must be used in the place of the whole value $stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");$stmt->execute(array("%$_GET[name]%"));?> \[/code\]I tried this, and even though I no longer get a Warning, I do not get any results. However when I execute the query directly I will get a couple of results. Any thoughts?
 
Back
Top