【问题标题】:how do i use LIKE in PDO?我如何在 PDO 中使用 LIKE?
【发布时间】:2020-07-27 19:00:07
【问题描述】:

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

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

?>

请帮忙

【问题讨论】:

    标签: php pdo sql-like


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-12
        • 2012-11-29
        相关资源
        最近更新 更多