Search code examples
phppdosql-like

how do i use LIKE in PDO?


i'm trying to use LIKE with my sql query in php. but it only displays when the search query is exactly the same. this is my code below.

<?php
include 'config.php';

$sql = "select name, skill, Location, phone, rating FROM searchResults WHERE skill LIKE :search OR name LIKE :search order by id desc";

try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->prepare($sql);  
    // $stmt->bindParam("search", $_GET['search']);
    $stmt->bindValue(":search", $_GET['search'], PDO::PARAM_STR);
    $stmt->execute();
    $employees = $stmt->fetchAll(PDO::FETCH_OBJ);
    $dbh = null;
    echo '{"items":'. json_encode($employees) .'}'; 
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
}

?>

please help


Solution

  • In your example, you can simply do

    $stmt->bindValue(":search", "%" . $_GET['search'] . "%", PDO::PARAM_STR);