1

I have a json data like this:

[{"data1":"body1"},{"data1":"body2"}]

I want to insert data1 to my database with this

php code:

<?php
$query = mysql_query("INSERT INTO data VALUES('$datadecode')");
?> 

but data json is not always 2 array, How can I insert it all to my Database ?

1
  • you need to use foreach or for loop Commented Apr 26, 2016 at 7:09

3 Answers 3

1

Use json_decode() and loop over decoded array.

Use MySQL's multiple row insert.

<?php
$json = '[{"data1":"body1"},{"data1":"body2"}]';
$arr = json_decode($json, TRUE);
if (! empty($arr)) {
 $values = array();
 foreach ($arr as $elem) {
  $values[] = "('". $elem['data1'] ."')";
 }
 if (! empty($values)) {
  $sql = "INSERT INTO data VALUES";
  $sql.= implode(', ', $values);
 }
}
echo $sql;
// Outputs
// INSERT INTO data VALUES('body1'), ('body2')
?>
Sign up to request clarification or add additional context in comments.

3 Comments

why after insert to mysql it return 0 ?
Print and paste sql here.
after i print it return 1
0

Do something like this :

<?php
$json = '[{"data1":"body1"},{"data1":"body2"}]';
$arr = json_decode($json);
if (! empty($arr)) {
    $val = array();
    foreach ($arr as $elem) {
        $val[] = ($elem['data1']);
    }

    $vlaues= implode(', ', $val);
    if (! empty($values))
        $sql = "INSERT INTO data VALUES ('".$val."')";
}
?>

Comments

0

Just use json_decode to decode the json into array. Use second parameter as true for associative array.

PHP

$json = '[{"data1":"body1"},{"data1":"body2"}]';

$arr = json_decode($json, true);
echo $datadecode = $arr['0']['data1'];

Ourput:

body1

Now you can use this variable onto the query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.