php - 如何在带有 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;
}
推荐阅读
- javascript - 用于在字符串中的数字和运算符符号之间添加空格的 JavaScript 正则表达式
- python - pyspark 中用于 RDD 对象的方法
- java - 使用docker镜像中的sh文件无法执行maven命令
- javascript - 使用subscriptionItems(或删除并再次添加subscriptionItem)并处理订阅日期来源时取消取消条带订阅
- android - 无法连接到开发服务器 - REACT NATIVE - ANDROID STUDIO
- node.js - 使用 AWS 部署 PRN 堆栈应用程序
- angular - 在 VS Code 中切换选项卡会导致 Angular 进行热重载
- javascript - 为 PHP 中的 HTML 下拉菜单格式化 XML 响应
- python - 为什么说 USER_SETUP 不是未使用的变量?不和谐
- c - 为什么 scanf 的错误不会让它消耗输入缓冲区?