I have managed to create a JSON code for data I retrieved from my API source, however dont know how to store the retrieved data (a more cleaner code to quickly manage and store the data)
Here is my Code that I use to retrieve the API data: (Working)
// VERIFY IF ID IS VALID USING API
$url = $apiURL.$apiKey.$apiSer.$apiJsn.$id;
$json = file_get_contents($url);
$data = json_decode($json);
$verify = $data->{'Response'};
// VERIFY IF RESPONSE IS TRUE
if ($verify == 'True') {
// LOOP
foreach ($data as $key => $jsons) {
// echo $jsons.'<br>';
// HERE I NEED HELP TO STORE THE DATA TO MYSQL!!!
}
} else {
// RETURN ERROR
echo 'RESPONSE IS FALSE';
}
}
JSON Code from API:
{"Title":"Title Name",
"Name":"User Name",
"Surname":"User Surname",
"Email":"User Email",
.....................}
What I normally would do to store the data:
$query = dbConnect()->prepare("INSERT INTO _users (name, surname, email, ....) VALUES (:1, :2, :3,....)");
$query->bindParam(':1', $name);
$query->bindParam(':2', $surname);
$query->bindParam(':3', $email);
....
if($query->execute()){
echo "<div class='alert alert-success' align='center'>
<strong>Product has been created!</strong>
</div>";
}
The values from the JSON API is the same as the database structure.
Is there a better way to import the data to my database?
Firstly change,
$data = json_decode($json);
to,
$data = json_decode($json, true);
to return the JSON data as an associative array then assuming you only have one row,
/** Prepare query before the loop not in the loop... **/
foreach ($data as $key => $value) {
/** BIND HERE - $key => Title, Name, Surname and Email **/
}
/** Execute here... **/
$stmt->execute();
otherwise you'd execute within the foreach
loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.