javascript - 将JSON数据存储在数据库: object could not be converted to string error中

标签 javascript php mysql ajax json

简而言之,我的数据是用 Javascript 编写的:

JSONdata = {
    name: form.name.value,
    address1: form.custa.value,
    address2: form.custa2.value,
    postcode: form.custpc.value,
    order: fullorder,
    cost: document.getElementById('total')
  }

fullorder 是要订购的产品数组。 : [{"idnum":"2","cost":232,"quantity":"1"},{"idnum":"1","cost":2342,"quantity":"3"}]

我有一个 XJAX,它可以将此数据字符串化,如下所示:

{"name":"j","address1":"jh","address2":"jhj","postcode":"h","order":[{"idnum":"2","cost":232,"quantity":"1"},{"idnum":"1","cost":2342,"quantity":"3"}],"cost":{}}

在 PHP 中,它以数组形式给出:

    Array
(
    [0] => stdClass Object
        (
            [idnum] => 2
            [cost] => 232
            [quantity] => 1
        )

    [1] => stdClass Object
        (
            [idnum] => 1
            [cost] => 2342
            [quantity] => 3
        )

)

我的问题是如何将其存储在数据库中? 我尝试过序列化和 json_encode 但都给了我一个: “stdClass 类的对象无法转换为字符串”。

任何帮助将不胜感激!

-> 不用担心查询数据库和JSON之争。 我将立即获取所有数据,所以这不是问题:)

编辑:感谢大家的回复,我向您提供一些有关其工作原理的信息:

因此,当我将 JSON 发送到 PHP 时,我有一个脚本可以像这样提取所有数据:

$intel = extractdata();
function extractdata() {
    if (isset($_REQUEST['data'])){
    $jsonDump = json_decode($_REQUEST['data']);
  foreach($jsonDump as $key => $value) {
    $obj[$key] = $value;
  }
  return $obj;
}

所以这给了我

$intel['name'] = // form.name.value variable
$intel['address1'] = // form.name.value variable

并且 $intel['order'] 为我提供了上面看到的 PHP 数组。我想将所有这些存储到数据库的列中:客户名称、地址1、地址2、邮政编码、订单、成本

我认为只需 $neworder = json_encode($intel['order']) 就可以让我将其存储在数据库中,但它仍然会引发转换错误。

谢谢

最佳答案

所以基本上你有一个包含这样的对象的数组:

$o = array((Object)array(array("idnum"=>2, "cost"=>232, "quantity"=>1), array("idnum"=>1, "cost"=>2342, "quantity"=>3)));

使用 json_encode() 回显将返回一个 json 字符串:

echo json_encode($o);

结果将是

[
  {
    "0": {
      "idnum": 2,
      "cost": 232,
      "quantity": 1
    },
    "1": {
      "idnum": 1,
      "cost": 2342,
      "quantity": 3
    }
  }
]

这不适合你吗?您还使用任何框架还是仅使用纯 php?

关于javascript - 将JSON数据存储在数据库: object could not be converted to string error中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23336394/

相关文章:

javascript - 递归地 react : Adding props only to React component and not html tag (React. Children.map)

php - JSON:字符集和获取键/值

php - 使用 PHP 对象设置递归属性是否安全?

mysql - 如何在mysql中创建没有索引或键的临时表?

mysql - 局域网PC无法连接MySQL服务器

javascript - 与多个页面上的 div 同步内容

javascript - 以 Angular 从子级更新父级范围

javascript - 将 PHP var 传递给 js 函数

php - 具有相同类名的命名空间

mysql - 在 MySQL 中使用字符串枚举 - 性能问题