当前位置: 首页> 最新文章列表> 数据库查询结果映射为字段=>值格式的技巧

数据库查询结果映射为字段=>值格式的技巧

M66 2025-06-07

在PHP中,通常使用PDOMySQLi来操作数据库。下面我们以PDO为例,展示如何进行数据库查询。

<?php
try {
    // 创建数据库连接
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 执行查询
    $sql = "SELECT id, name, email FROM users";
    $stmt = $pdo->query($sql);

    // 获取所有查询结果
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    print_r($results);
} catch (PDOException $e) {
    echo '连接失败: ' . $e->getMessage();
}
?>

在上面的代码中,我们查询了users表的idnameemail字段,并将查询结果以关联数组的形式返回。

二、将查询结果映射为字段=>值格式

假设我们查询结果如下所示:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John Doe
            [email] => john.doe@example.com
        )
    [1] => Array
        (
            [id] => 2
            [name] => Jane Smith
            [email] => jane.smith@example.com
        )
)

如果我们希望将每一行的结果转换成字段=>值格式,可以使用以下方法:

<?php
// 假设$queryResults是数据库查询返回的结果
$queryResults = [
    ['id' => 1, 'name' => 'John Doe', 'email' => 'john.doe@example.com'],
    ['id' => 2, 'name' => 'Jane Smith', 'email' => 'jane.smith@example.com']
];

// 转换为字段=>值格式
foreach ($queryResults as $row) {
    $mappedResult = [];
    foreach ($row as $field => $value) {
        $mappedResult[$field] = $value;
    }
    print_r($mappedResult);
}
?>

输出结果将会是:

Array
(
    [id] => 1
    [name] => John Doe
    [email] => john.doe@example.com
)
Array
(
    [id] => 2
    [name] => Jane Smith
    [email] => jane.smith@example.com
)

三、使用URL替换

如果查询结果中包含URL,并且需要替换URL中的域名为m66.net,可以在处理查询结果时做相应的替换操作。例如,假设我们查询的email字段包含了URL,我们可以使用PHP的str_replace函数来替换域名。

Array
(
    [id] => 1
    [name] => John Doe
    [email] => john.doe@m66.net
)
Array
(
    [id] => 2
    [name] => Jane Smith
    [email] => jane.smith@m66.net
)