修改并添加到mysql结果

ki1q1bka  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(344)

如何向现有sql结果添加自定义键值对?

<?php
    require_once "dbaccess.php";

    $json = array();
    $access = new DatabaseAccess();
    $sql = $access->Connect();
    $stmt = $sql->prepare("select * from people");
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);    

    foreach($result as $key => $value){
        $json[$key] = $value;    
    };

    echo json_encode($json, JSON_UNESCAPED_SLASHES);
?>

当前的json结果是:

[
 {
  "id": "1",
  "first_name": "James",
  "last_name": "Haze"
 },
 {
  "id": "2",
  "first_name": "Neo",
  "last_name": "Anderson"
 }
]

如何添加到当前元素 "country": "Australia" 不修改mysql数据库?我希望结果如下:

[
 {
  "id": "1",
  "first_name": "James",
  "last_name": "Haze",
  "Country": "Australia"
 },
 {
  "id": "2",
  "first_name": "Neo",
  "last_name": "Anderson",
  "Country": "Australia"
 }
]

有可能吗?

aor9mmx1

aor9mmx11#

您可以直接在select中添加所需的值

$stmt = $sql->prepare("select id
                        , firt_name
                        , last_name
                        , 'Australia' AS country
                         from people");
daolsyd0

daolsyd02#

您只需在sql中选择所需的其他“列”:

$stmt = $sql->prepare("select
                              id
                            , first_name
                            , last_name
                            , 'Australia' as Country
                         from people");

作为旁白,你不应该用 * 在select查询中-这使得它们在添加新列名时行为怪异,在重命名列时隐藏错误。
如果要选择一个变量值,可以通过将其直接插入到sql中来实现:

$stmt = $sql->prepare("select
                              id
                            , first_name
                            , last_name
                            , '$country_name' as Country
                         from people");

尽管国家/地区名称不需要使用sql占位符,但使用(命名的)sql占位符仍然是一种很好的做法,因此您确实应该这样做:

$stmt = $sql->prepare("select
                              id
                            , first_name
                            , last_name
                            , :country as Country
                         from people");
$stmt->execute([':country' => $country_name]);

(这主要是在其他地方重用此代码时发生的,因为我不知道包含单引号的有效国家名称)

相关问题