这是我的json解码代码,解码后插入表中。我没有得到如何将implode值插入表和嵌套的json值。
include 'config.php'; /* datdabase connection*/
class User {
public function update()
{
$jsondata = file_get_contents('data.txt');
$data = json_decode($jsondata, true);
$name=array();
foreach($data as $item)
{
$name[]=$item['v'];
}
$val=implode(',',$name);
echo"$val";
$sql= mysql_query("INSERT INTO incident_main(inc_patientName,inc_patientAge,inc_patientGender,inc_patientMobile,inc_patientAddress,inc_patientWard,inc_type) VALUES('..........') )");
if(!$sql)
{
echo "Failed to insert the data into table";
}
}}
$obj=new User();
$obj->update()
这是我的data.txt文件。这里“n”是表格列的名称,“v”是要插入的值。
{
"user_id": "user123",
"time_stamp": "epoch",
"lat": 52.25,
"lon": 85.45,
"mainreport": [{
"n": "date_of_diagnosis",
"v": "epoch"
},
{
"n": "name",
"v": "abc"
},
{
"n": "age",
"v": 20
},
{
"n": "gender",
"v": "male"
},
{
"n": "address",
"v": "some address"
},
{
"n": "location_gis_Stamp",
"v": "word-1"
},
{
"n": "mobile_number",
"v": "some number"
},
{
"n": "type_of_application",
"v": "other",
"nested": [{
"n": "other",
"v": "reason"
}]}]}
答案 0 :(得分:0)
您的查询中有以下错误
incident_main(inc_patientName,inc_patientAge,........
)
近值。 inc_treatment,inc_untraced) VALUES('..........') )"
''
。试试这样:
foreach($data as $item)
{
$name[]=$item['v'];
// Check and get Nested Values
if( isset($item['nested']) && is_array($item['nested']) ) {
foreach($item['nested'] as $val) {
$name[] = $val['v'];
}
}
}
$val=implode("','",$name);
// epoch', 'abc', '20', 'male', 'some address', 'word-1', 'some number', 'other', 'reason
$sql= mysql_query("INSERT INTO incident_main (inc_patientName,inc_patientAge,inc_patientGender,inc_patientMobile,inc_patientAddress,inc_patientWard,inc_type,inc_diagnosis,inc_recurrence,inc_hospitalized,inc_treatment,inc_untraced)
VALUES('".$val."') ");
请使用mysqli
或PDO
代替mysql_*
答案 1 :(得分:0)
值应使用引号。请试试这个;
$val='"' . implode('","',$name) . '"';
$sql= mysql_query("INSERT INTO incident_main(inc_patientName,inc_patientAge,inc_patientGender,inc_patientMobile,inc_patientAddress,inc_patientWard,inc_type,inc_diagnosis,inc_recurrence,inc_hospitalized,inc_treatment,inc_untraced) VALUES($val);");
另外,在PHP 5.5中不推荐使用mysql_函数。使用PDO或mysqli代替mysql_函数。
答案 2 :(得分:0)
要使用这些值,您可以在sql中将其替换为:
$sql = "INSERT INTO incident(inc_patientName,inc_patientAge,inc_patientGender,inc_patientMobile,inc_patientAddress,inc_patientWard,inc_type,inc_diagnosis,inc_recurrence,inc_hospitalized,inc_treatment,inc_untraced)". " VALUES( '".$val."')";
上面的代码将给出以下结果:
INSERT INTO 事件(inc_patientName,inc_patientAge,inc_patientGender,inc_patientMobile,inc_patientAddress,inc_patientWard,inc_type,inc_diagnosis,inc_recurrence,inc_hospitalized,inc_treatment,inc_untraced)VALUES(' epoch',' abc',' 20','男','某些地址','字-1','某些 数''其他&#39)
但是,在您的代码中,您使用","来破坏值。 ,但在sql中 字符串值用双引号""
编码
要解决此问题,请按以下步骤更换代码:
$val=implode("','",$name);