Japar S Japar S - 2 years ago 66
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 ?

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download