循环json数据然后用PHP发送到数据库

时间:2017-07-25 08:25:02

标签: javascript php jquery json

我有这样的json数据:

myjsondata

[

{
"id_user":"31"
},

{
"id_user":"32"
},

{
"id_user":"33"
}

]

然后我用jquery $ .post

发送数据
$.post("myaction.php",
{send: myjsondata }, function(res) {


 }, "json");

然后在myaction.php中,我解码了json,我想用foreach将数据发送到数据库:

myaction.php

$conn = mysqli_connect( "localhost","root","","mydb");

$data = json_decode($_POST['send']);

foreach($data as $row){

    $id_user = $row->id_user;

}

mysqli_query($conn, "INSERT INTO tbl_user 
(id_user) VALUES ('$id_user') ");

当我运行该代码时,数据已经插入到表中,但数据只插入了最后一个id_user

tbl_user

id_user

33

我希望所有数据都像这样插入到表中

tbl_user

id_user

31
32
33

我该怎么做? 感谢

4 个答案:

答案 0 :(得分:2)

嗯,这完全是逻辑。让我们来看看你的代码:

$conn = mysqli_connect( "localhost","root","","mydb");

$data = json_decode($_POST['send']);

foreach($data as $row){

    $id_user = $row->id_user;

}

mysqli_query($conn, "INSERT INTO tbl_user 
(id_user) VALUES ('$id_user') "); // Here is the problem!!!!

在foreach循环中,您将覆盖$id_user变量。然后只在最后插入。所以,你可以做什么?只需将插入查询放在foreach循环中即可。

工作解决方案:

$conn = mysqli_connect( "localhost","root","","mydb");

$data = json_decode($_POST['send']);

foreach($data as $row){

    $id_user = $row->id_user;
    mysqli_query($conn, "INSERT INTO tbl_user 
    (id_user) VALUES ('$id_user') "); 

}

答案 1 :(得分:1)

您需要将查询移动到for循环

$conn = mysqli_connect( "localhost","root","","mydb");

$data = json_decode($_POST['send']);

foreach($data as $row){

    $id_user = $row->id_user;

    mysqli_query($conn, "INSERT INTO tbl_user (id_user) VALUES ('$id_user') ");
}

答案 2 :(得分:1)

第一名:将您的query移到foreach loop

foreach($data as $row){

    $id_user = $row->id_user;

    mysqli_query($conn, "INSERT INTO tbl_user (id_user) VALUES ('$id_user') ");
}

第二名:尝试使用预备声明

原因: foreach循环中的overwriting $id_user以及foreach循环后执行的查询,因此$id_user仅包含最后一行值.so移动查询进入foreach loop

答案 3 :(得分:1)

myaction.php文件将是这样的。

$conn = mysqli_connect( "localhost","root","","mydb");

$data = json_decode($_POST['send']);

foreach($data as $row){

    $id_user = $row->id_user;

    mysqli_query($conn, "INSERT INTO tbl_user (id_user) VALUES ('$id_user') ");
}