如何拆分句子为单词并查询MySQL中含匹配单词的行
解决方案
你的问题在于当前SQL语句是匹配完整的句子字符串,但你需要的是匹配句子中任意单个单词的行,同时直接拼接变量到SQL里存在严重的SQL注入风险,下面是修正后的实现:
步骤说明
- 将目标句子拆分为独立单词,过滤无效空值
- 构建安全的SQL查询条件(使用预处理语句避免注入)
- 绑定参数并执行查询,输出匹配结果
完整代码
<?php $servername = "localhost"; $username = "dsfdsfds"; $password = "sdfdfsdsf"; $dbname = "sdf"; // 建立数据库连接 $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $targetSentence = "This is a sentence"; // 1. 拆分句子为单词数组,过滤空字符串(处理多空格情况) $words = array_filter(explode(' ', strtolower($targetSentence))); $wordCount = count($words); if ($wordCount === 0) { echo "No valid words to search"; $conn->close(); exit; } // 2. 构建SQL查询条件:每个单词对应一个LIKE ?,用OR连接 $conditions = array_fill(0, $wordCount, "LOWER(origin) LIKE ?"); $sql = "SELECT * FROM rawwords WHERE " . implode(" OR ", $conditions); // 使用预处理语句防止SQL注入 $stmt = $conn->prepare($sql); if (!$stmt) { die("Prepare failed: " . $conn->error); } // 3. 绑定参数:每个单词需要加%通配符,匹配任意位置出现的单词 $params = array_map(function($word) { return "%$word%"; }, $words); // 绑定参数类型(s表示字符串,重复$wordCount次) $types = str_repeat('s', $wordCount); $stmt->bind_param($types, ...$params); // 执行查询 $stmt->execute(); $result = $stmt->get_result(); // 输出结果 if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - location: " . $row["sentence"]. " <br><br>"; } } else { echo "0 results"; } // 关闭资源 $stmt->close(); $conn->close(); ?>
关键细节说明
- 使用
strtolower()和LOWER(origin)确保查询不区分大小写,如果你需要严格区分大小写,可以去掉这两个转换 array_filter()用来过滤拆分后可能出现的空字符串(比如句子开头/结尾的空格,或者连续空格)- 预处理语句
bind_param()安全处理用户输入,彻底避免SQL注入风险 - 每个单词前后添加
%通配符,确保能匹配到单词出现在字段任意位置的行
内容的提问来源于stack exchange,提问作者James Shelton
相关产品推荐
相关产品推荐

