gpt4 book ai didi

php - 将静态值添加到 PDO 结果行

转载 作者:行者123 更新时间:2023-12-02 03:59:25 25 4
gpt4 key购买 nike

我想将静态声明的元素 (saved_id) 添加到数据库查询结果填充的行数据中。

这是我的代码:

$stmt = $db->prepare("SELECT * FROM wishlists WHERE user_id='1'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$res = array('saved_id' => "1");
array_push($result, $res);
echo json_encode($result);

当前结果:

[{"id":"1","user_id":"1","name":"San Francisco","privacy":"0","pick":"Yes"},{"saved_id":"1"}]

期望的结果:

[{"id":"1","user_id":"1","name":"San Francisco","privacy":"0","pick":"Yes","saved_id":"1"}]

最佳答案

如果需要多个结果,直接在查询中注入(inject)所需的值会更简单:

$saved_id = 1;
$user_id = 1;
$stmt = $db->prepare("SELECT *, ? as saved_id FROM wishlists WHERE user_id=?");
$stmt->execute([$saved_id, $user_id]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);

但是如果您只需要一行,则必须使用 fetch() 而不是 fetchAll()
在这种情况下,您可以稍后将任何元素添加到获取的行中:

$user_id = 1;
$stmt = $db->prepare("SELECT * FROM wishlists WHERE user_id=?");
$stmt->execute([$user_id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$result['saved_id'] = "1";
echo json_encode($result);

关于php - 将静态值添加到 PDO 结果行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42530105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com