I failed with this. Despite all the answers here, I just cannot get this right. How do I bind a search term when using like
in mysql with php's pdo?
$searchTerm = 'kfc';
$stmt = $conn->prepare("select name from table where name like CONCAT('%',:searchTerm,'%')");
$stmt->bindParam(':searchTerm', $searchTerm);
or
$searchTerm = 'kfc';
$stmt = $conn->prepare("select name from table where name like %:searchTerm%");
$stmt->bindParam(':searchTerm', $searchTerm);
Neither will work for me. How do I get this correct?
You're missing the LIKE
clause in both the queries. bindParam
will automatically take care of all the quoting, so you don't need to add single-quotes around the search term.
This should work:
$searchTerm = 'kfc%';
$stmt = $conn->prepare("select name from table where name LIKE :searchTerm");
$stmt->bindParam(':searchTerm', $searchTerm);
While second one makes no sense, first approach is seemingly correct. You should try harder to make it work. May be there is just no data in the table to match the search term.