我得到以下JSON格式的数据。
{"Students":
[{"ID":"600","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"601","datetime":"26-11-2019 04-32-31","age":"13"},
{"ID":"602","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"603","datetime":"26-11-2019 04-32-31","age":"14"}
]}我想编写一个PHP脚本来在MYSQL中插入这些数据。
我不知道如何编写循环来遍历这些数据。
我尝试了下面的代码,但它不起作用。
//encode the Json request.
$obj = json_decode($content);
foreach($obj as $key){
// $email = $decode['RouteID'];
}发布于 2019-11-28 13:21:34
// creating connection to mysql
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=DatbaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$content = '{"Students":
[{"ID":"600","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"601","datetime":"26-11-2019 04-32-31","age":"13"},
{"ID":"602","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"603","datetime":"26-11-2019 04-32-31","age":"14"}
]}';
$data= json_decode($content);
foreach($data->Students as $student){
$sql = "INSERT INTO users (ID, datetime, age) VALUES (?,?,?)";
$conn->prepare($sql)->execute([$student->ID, $student->datetime, $student->age]);
}https://stackoverflow.com/questions/59089726
复制相似问题