【问题标题】:How do I use the like operator in SQL with php user input? [duplicate]如何在带有 php 用户输入的 SQL 中使用 like 运算符? [复制]
【发布时间】:2019-12-18 22:58:28
【问题描述】:
$search_query = mysqli_real_escape_string($conn, $_POST['this']);
$sql = "SELECT this FROM that WHERE this LIKE ' '%' + " .$search_query. " + '%' '";

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

【问题讨论】:

  • 您在LIKE 和您的语句末尾放错了单引号。应该是:$sql = "SELECT this FROM that WHERE this LIKE '%' + '" .$search_query. "' + '%' ".
  • @GMB 那时我可能做得不对,因为我无法回显结果。如果我这样做 $result = mysqli_query($conn, $sql); $row = mysqli_fetch_assoc($result); echo mb_substr($row["this"]);
  • 呼应@GMB 拜托拜托使用准备好的陈述!像你这样编写 SQL 命令非常不安全
  • MySQL 不使用+ 进行字符串连接,它使用CONCAT() 函数。

标签: php mysql sql mysqli


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多