I have a json data like this:
我有这样的json数据:
[{"data1":"body1"},{"data1":"body2"}]
I want to insert data1
to my database with this
我想用这个将data1插入我的数据库
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 ?
但是数据json并不总是2个数组,如何将它全部插入到我的数据库中?
3 个解决方案
#1
1
Use json_decode() and loop over decoded array.
使用json_decode()并循环解码数组。
Use MySQL's multiple row insert.
使用MySQL的多行插入。
<?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')
?>
#2
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."')";
}
?>
#3
0
Just use json_decode
to decode the json into array. Use second parameter as true for associative array.
只需使用json_decode将json解码为数组。对于关联数组,将第二个参数用作true。
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.
现在,您可以将此变量用于查询。
#1
1
Use json_decode() and loop over decoded array.
使用json_decode()并循环解码数组。
Use MySQL's multiple row insert.
使用MySQL的多行插入。
<?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')
?>
#2
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."')";
}
?>
#3
0
Just use json_decode
to decode the json into array. Use second parameter as true for associative array.
只需使用json_decode将json解码为数组。对于关联数组,将第二个参数用作true。
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.
现在,您可以将此变量用于查询。