如何将数据从json对象插入数据库

时间:2015-05-14 08:50:59

标签: php sql json

我对json很新,但我试图将一些数据从json插入到数据库表中。我不断收到一些错误: 注意:未定义的索引:主题 注意:未定义索引:消息

<?php
$jsondata = '{
  "p1" : [
{
"subject": "Something",
"message": "Something"
},
{
"subject": "Something111",
"message": "Something11"
}
]
}';

$data = json_decode($jsondata, true);
$p1 = $data['p1'];

$sql = "INSERT INTO 
        table(subject,
        message)
        VALUES('".$p1['subject]."', '".$p1['message]."'");
$result = $mysqli->query($sql);

?>

4 个答案:

答案 0 :(得分:0)

$ p1是一个数组对象,例如:{&#34; subject&#34;:&#34; xxxx&#34;,&#34; message&#34;:&#34 ; YYY&#34;};

因此,您必须循环 $ p1并执行db insert

foreach ($p1 as $obj){
    $sql = "INSERT INTO 
    table(subject,
    message)
    VALUES('".$obj['subject]."', '".obj['message]."'");
    ...
}

答案 1 :(得分:0)

$ p1中有多维数组 如果你想插入第一行,你可以使用它。否则你需要使用foreach

$ sql =&#34; INSERT INTO         表(主题,         信息)         价值观(&#39;&#34;。$ p1 [0] [&#39;主题&#39;]。&#34;&#39;,&#39;&#34;。$ p1 [0] [&#39;消息&#39]。&#34;&#39;)&#34 ;;

答案 2 :(得分:0)

您的代码中存在许多错误。

1. $ p1是您作为数组处理的多维数组

2.您在查询中忘记了逗号(&#39;)

3.你已经关闭了#34;在查询中的错误位置,它应该在值括号后最后。

使用此代码

$jsondata = '{
  "p1" : [
{
"subject": "Something",
"message": "Something"
},
{
"subject": "Something111",
"message": "Something11"
}
]
}';

$data = json_decode($jsondata, true);
$p1 = $data['p1'];
foreach($p1 as $val)
{
    $sql = "INSERT INTO table(subject,message) VALUES('".$val['subject']."', '".$val['message']."')";
    $result = $mysqli->query($sql);
}

答案 3 :(得分:0)

foreach loop will do the job but as it is an object you need to access it using the -> operator.


    <?php
    $jsondata = '{
    "p1" : [
    {
    "subject": "Something",
    "message": "Something"
    },
    {
    "subject": "Something111",
    "message": "Something11"
    }
    ]
    }';
    $data = json_decode($jsondata, true);
    $p1 = $data['p1'];
    foreach ($p1 as $object){
   $sql = "INSERT INTO  table(subject,message) VALUES ('".$object->subject."','".$object->message."'");
    $result = $mysqli->query($sql);
    }
    ?>


I hope this helps you