PHP MySQL在准备好的语句中搜索%John D%这样的名称

时间:2018-02-21 08:28:34

标签: php mysql mysqli

我正在尝试查找与搜索匹配的人名列表。我的php:

require "accessControl.php";
require "sqlLink.php";

$string = "%dan%";

// create a prepared statement
if ($stmt = $link->prepare("SELECT full_name FROM (SELECT *, CONCAT(firstname," ",lastname) AS full_name FROM users) tmp WHERE full_name LIKE ?")) {

    $stmt->bind_param("s", $string);

    $stmt->execute();

    $stmt->bind_result($result);

    $stmt->fetch();

    $stmt->close();
}

echo $result;

这只会产生500错误,但当我用"SELECT lastname FROM users WHERE firstname LIKE ?"替换查询时,它可以正常工作。我花了一个多小时寻找解决方案,但我很困惑。

2 个答案:

答案 0 :(得分:3)

if中的条件替换为:

$stmt = $link->prepare("SELECT full_name FROM (SELECT *, CONCAT(firstname,' ',lastname) AS full_name FROM users) tmp WHERE full_name LIKE ?")

在这里,您只需要在" "函数中将' '替换为CONCAT(),因为这会破坏整个字符串,该字符串也以"开头和结尾。

答案 1 :(得分:1)

首先不要使用“”里面的duoble引用字符串..因为打破了字符串的连续性。 第二,你可以使用concat为wilchar构建字符串

$string = "dan";
$link->prepare("SELECT full_name FROM (
                SELECT *, CONCAT(firstname,' ',lastname) AS full_name FROM users
              ) tmp WHERE full_name LIKE concat( '%', ?, '%'))");