我正在尝试运行一些简单的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"
}
}
答案 0 :(得分:0)
服务器返回的此JSON字符串无效。无法用json_decode解析。
答案 1 :(得分:0)
您的JSON无效。见下文。
"profile":{
"designation":"Deputy General",
"department":"Finance", //Remove Comma here for valid JSON
}
您可以使用var_dump()
上的json_decode()
对此进行测试,然后使用JSON Validation tool验证您的JSON字符串。
答案 2 :(得分:0)
原始问题中URL的已提交JSON无效。这就是json_decode()
返回false
并隐式将空值推送到数据库的原因。
然而,问题中的源代码有一堆我想概述的缺陷。您正在加载,解析和放入数据库的外部源可能包含恶意信息。不要信任从外部源检索的数据,并过滤或清理值。
如果远程源包含某些类似SQL的信息(无论出于何种原因),您的Web应用程序将容易受到SQL注入。
关于你的代码,这意味着两个基本的例子:
$connection = new \PDO(
'mysql:dbname=database_name;host=127.0.0.1',
$username,
$password
);
// cast to integer values if that's the expected type
$id = (int)$data['empid'];
// escape literals and "disarm" injected statements
$streetaddress = $connection->quote(
$data['personal']['address']['streetaddress']
);
使用预处理语句将是绕过这些SQL注入可能性的建议。除此之外,您可以考虑使用类似Doctrine DBAL或PDO的框架或包装器来进一步在PHP中进行数据库开发。