Following prepared statement returns no result if I try like search('samsung').
public function search($searchFor) {
try{
//connect to db
$pdo = $this->_db->connect();
//set up SQL and bind parameters
$sql = "select * from item where itemName like '%:searchfor%' or description like '%:searchfor%'";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':searchfor', $searchFor, PDO::PARAM_STR);
//execute SQL
$rows = $this->_db->executeSQL($stmt);
return $rows;
}
catch (PDOException $e)
{
throw $e;
}
}
$rows return an empty array. But if I try
select * from item where itemName like '%samsung%' or description like '%samsung%;
it returns a matched item and works as expected.
I found
$sql = "select * from item where itemName like :searchfor or description like :searchfor";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":searchfor", "%$searchFor%");
works. I had to use bindValue instead. This was a totally different issue in that the SQL was correct but I used bindParam instead of bindValue (which is the correct method), hence this is not a duplicate.