简体   繁体   中英

Looping json data then send to database with php

I have json data like this :

myjsondata

[

{
"id_user":"31"
},

{
"id_user":"32"
},

{
"id_user":"33"
}

]

then i send the data with jquery $.post

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


 }, "json");

then in myaction.php, i decode the json and i want to send the data to database with 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') ");

when i running that code, the data already inserted to the table , but the data only inserted with last id_user

tbl_user

id_user

33

i want all data is inserted into the table like this

tbl_user

id_user

31
32
33

how can i do that? thanks

Well, thats totally logic. Lets take a look at your code:

$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!!!!

In your foreach loop you overwrite the $id_user variable. Then only at the end you insert. So what can you do? Simply put the insert query inside the foreach loop and it will work.

Working solution:

$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') "); 

}

You need to move the query into the for loop

$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') ");
}

1st: Move your query into inside the foreach loop

foreach($data as $row){

    $id_user = $row->id_user;

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

2nd : Try to use prepared statement

Cause : your overwriting $id_user in foreach loop and your executing query after foreach loop so $id_user only contains last row value only .so Move your query into inside the foreach loop

myaction.php File will be like this .

$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') ");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM