Japar S Japar S - 7 months ago 26
PHP Question

Insert to mysql from json data with object more than 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 ?

Answer

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')
?>