gpt4 book ai didi

php - 空值被错误地插入到 MySQL 数据库中

转载 作者:行者123 更新时间:2023-11-30 22:11:18 27 4
gpt4 key购买 nike

我正在尝试运行一些简单的 PHP 代码,以提取 JSON 格式的文件并插入到数据库中。

代码返回一条新记录已成功创建。但是,当我查看数据库时,每个值都是 0。

//read the json file contents
$jsondata = file_get_contents('http://tally.fit/empdetails.json');

//convert json object to php associative array
$data = json_decode($jsondata, true);

//get the employee details
$id = $data['empid'];
$name = $data['personal']['name'];
$gender = $data['personal']['gender'];
$age = $data['personal']['age'];
$streetaddress = $data['personal']['address']['streetaddress'];
$city = $data['personal']['address']['city'];
$state = $data['personal']['address']['state'];
$postalcode = $data['personal']['address']['postalcode'];
$designation = $data['profile']['designation'];
$department = $data['profile']['department'];

//insert into mysql table
$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city, state, postalcode, designation, department)
VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state', '$postalcode', '$designation', '$department')";

JSON:

{
"emp": "SJ011MS",
"personal": {
"name": "Smith Jones",
"gender": "male",
"age": "28",
"address": {
"streetaddress": "7 24th Street",
"city": "new york",
"state": "NY",
"postalcode": "10038"
}
},
"profile": {
"designation": "Deputy General",
"department": "Finance"
}
}

最佳答案

您的 JSON 无效。见下文。

"profile":{
"designation":"Deputy General",
"department":"Finance", //Remove Comma here for valid JSON
}

您可以在您的 json_decode() 上使用 var_dump() 来测试它,然后使用 JSON Validation tool 验证您的 JSON 字符串.

关于php - 空值被错误地插入到 MySQL 数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40051854/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com