php code example 2
php code example 2
<?php
// Assuming you have already established a connection to your MySQL database
// JSON data
$jsonData = '{
"users": [
{
"id": 1,
"name": "John Doe",
"email": "johndoe@example.com"
},
{
"id": 2,
"name": "Jane Smith",
"email": "janesmith@example.com"
}
]
}';
// Decode the JSON data into an associative array
$data = json_decode($jsonData, true);
// Access the "users" array within the JSON data
$users = $data['users'];
// Loop through each user and insert into the database
foreach ($users as $user) {
$id = $user['id'];
$name = $user['name'];
$email = $user['email'];
// Prepare the SQL statement
$stmt = $pdo->prepare("INSERT INTO users (id, name, email) VALUES (?, ?, ?)");
// Bind the parameters
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $name);
$stmt->bindParam(3, $email);
// Execute the statement
$stmt->execute();
}
// Close the database connection
$pdo = null;
?>