Japar S Japar S - 5 months ago 21x
PHP Question

Insert to mysql from json data with object more than 1

I have a json data like this:


I want to insert
to my database with this

php code:

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


Use json_decode() and loop over decoded array.

Use MySQL's multiple row insert.

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