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

PHP中如何将数据库查询字段值写入json_encode处理的数组

问题核心原因

  1. $stmt->fetchAll()返回的是包含所有匹配结果的二维数组,结构为$fetch[索引][字段名],你直接访问$fetch['price']不存在对应索引,自然无法拿到值。
  2. 你尝试的几种赋值写法均存在语法或逻辑错误:
    • 'amount' => ['price']直接赋值为包含字符串price的数组,和查询结果无关联
    • 双引号内嵌关联数组需要加花括号包裹,正确写法为"{$fetch['price']}",但该写法首先依赖$fetch的结构正确
    • 反引号在PHP中是执行系统命令的语法,完全不适用该场景
    • 直接写{$fetch['price']}无引号包裹,属于语法错误
  3. 现有预处理SQL直接拼接变量,存在SQL注入风险,没有正确使用参数绑定能力。

修复方案

场景1:仅需要获取最新1条产品的价格

将fetchAll()替换为fetch(),获取单条记录的一维关联数组即可,同时修复SQL注入问题:

// 预处理SQL使用参数占位符,避免注入
$stmt = $dbh->prepare("SELECT * FROM `products` WHERE `username` = ? ORDER BY `uid` DESC");
// 执行时传入参数
$stmt->execute([$_SESSION['usr_name']]);
// 取单条查询结果,返回一维关联数组
$product = $stmt->fetch();

// 可选校验:避免未查询到产品时出现报错
if (!$product) {
    die("未查询到对应用户的产品数据");
}

之后直接赋值即可:

'amount' => $product['price']

如果接口要求金额为保留两位小数的字符串,可调整为:

'amount' => number_format($product['price'], 2, '.', '')

场景2:需要遍历所有查询到的产品生成请求

将curl请求逻辑写在遍历$fetch的循环中即可:

$fetch = $stmt->fetchAll();
foreach ($fetch as $product) {
    // 此处写入curl请求逻辑,使用$product['price']赋值amount即可
}

修复后完整代码示例(单产品场景)

$userdetails = $_SESSION['usr_name'];
$stmt = $dbh->prepare("SELECT * FROM `products` WHERE `username` = ? ORDER BY `uid` DESC");
$stmt->execute([$userdetails]);
$product = $stmt->fetch();

if (!$product) {
    die("未查询到对应用户的产品数据");
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.commerce.coinbase.com/charges');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(
array (
    'name' => 'My-Business-Name',
    'description' => "Selected Product: {$product['item']}",
    'local_price' => array (
        'amount' => $product['price'],
        'currency' => 'GBP',
    ),
    'pricing_type' => 'fixed_price',
    'metadata' => array (
        'customer_id' => 'uid_1',
        'customer_name' => 'Satoshi Nakamoto',
    )
)));
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);

内容的提问来源于stack exchange,提问作者kbmzeeC0de

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:24:04