我如何在 PDO 中使用 LIKE?

how do i use LIKE in PDO?

我正尝试在 php 中对我的 sql 查询使用 LIKE。但它仅在搜索查询完全相同时显示。这是我下面的代码。

<?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() .'}}'; 
}

?>

请帮忙

您需要在 MySQL 查询中将搜索词放在 % 周围。检查 https://dev.mysql.com/doc/refman/8.0/en/pattern-matching.html

在你的例子中,你可以简单地做

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