如何在 PHP 用户输入中使用 SQL 中的 like 运算符?


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

这就是我目前所拥有的,这个语法有问题吗?

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

$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;
}

最新更新