Search code examples
phpmysqlpdogetsql-like

bindParam for a GET-value for LIKE in a PDO MySQL query


Is there any way of converting

$term = $_GET['p'];
$stmt = $dbh->prepare("
    SELECT      *
    FROM        posts
    WHERE       heading LIKE '%$term%'
    OR          full_text LIKE '%$term%'
    LIMIT       0 , 30
");
$stmt->execute();
$answer = $stmt->fetch(PDO::FETCH_ASSOC);

INTO something like

$term = "'%" . $_GET['p'] . "%'";
$stmt = $dbh->prepare("
    SELECT      *
    FROM        posts
    WHERE       heading LIKE :term
    OR          full_text LIKE :term
    LIMIT       0 , 30
");
$stmt->bindParam(":term", $term);
$stmt->execute();
$answer = $stmt->fetch(PDO::FETCH_ASSOC);

So that I can use bindParam(":term", $term); instead of '%$term%' in the query?

I've already looked at these Using LIKE in bindParam for a MySQL PDO Query and Mysql, PDO - Like statement not working using bindParam. But they doesn't give me any proper answer for my question.


Solution

  • Concatenate the wildcard symbols to the variable within SQL:

    $stmt = $dbh->prepare("
        SELECT      *
        FROM        posts
        WHERE       heading   LIKE CONCAT('%', :term, '%')
        OR          full_text LIKE CONCAT('%', :term, '%')
        LIMIT       0 , 30
    ");
    $stmt->bindParam(':term', $_GET['p']);
    $stmt->execute();
    $answer = $stmt->fetch(PDO::FETCH_ASSOC);