首页 > 解决方案 > 如何在带有 php 用户输入的 SQL 中使用 like 运算符?

问题描述

$search_query = mysqli_real_escape_string($conn, $_POST['this']);
$sql = "SELECT this FROM that WHERE this LIKE ' '%' + " .$search_query. " + '%' '";

这是我到目前为止所拥有的,这种语法有问题吗?

标签: phpmysqlsqlmysqli

解决方案


如果您使用准备好的语句重写查询,则不会遇到此类问题。例如:

$sql = 'SELECT this FROM that WHERE this LIKE ?';
$stmt = $conn->prepare($sql);
$search_query = '%' . $_POST['this'] . '%';
$stmt->bind_param('s', $search_query);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row['this'];
}

注意get_result仅适用于mysqlnd驱动程序,如果您没有,请将最后 4 行替换为

$stmt->bind_result($ths);
while ($stmt->fetch()) {
    echo $ths;
}

推荐阅读