You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拆分句子为单词并查询MySQL中含匹配单词的行

解决方案

你的问题在于当前SQL语句是匹配完整的句子字符串,但你需要的是匹配句子中任意单个单词的行,同时直接拼接变量到SQL里存在严重的SQL注入风险,下面是修正后的实现:

步骤说明

  1. 将目标句子拆分为独立单词,过滤无效空值
  2. 构建安全的SQL查询条件(使用预处理语句避免注入)
  3. 绑定参数并执行查询,输出匹配结果

完整代码

<?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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:36:00