使用 mysqli 实现基于 FIND_IN_SET 的多值匹配查询功能

发布时间:2025-06-13 08:23:41    发布者:文昌文城莱奥网络技术工作室    浏览次数:19

<?php
// 数据库连接配置
$host = 'localhost';
$user = 'your_db_user';
$password = 'your_db_password';
$database = 'your_db_name';

// 创建 mysqli 连接
$conn = new mysqli($host, $user, $password, $database);

// 检查连接是否成功
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// 要匹配的 ID 数组
$ids = [31, 52];

// 构建 FIND_IN_SET 条件
$conditions = array_map(function ($id) {
    return "FIND_IN_SET($id, your_field)";
}, $ids);

// 构建最终 SQL
$sql = "SELECT * FROM your_table WHERE " . implode(' OR ', $conditions);

// 执行查询
$result = $conn->query($sql);

// 处理结果
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // 输出每行数据
        print_r($row);
    }
} else {
    echo "No matching records found.";
}

// 关闭连接
$conn->close();