r/PHPhelp • u/Full_Astern • Apr 04 '23
Insert API data into MySQL
As a learning/test project, I'm trying to insert API data from a mega millions site into a database using PHP, but I'm not sure how to call "n5" in PHP based on the API response?
API response:
{
"success": true,
"result":
{
"numbers":
[ {
"date": "Fri, Nov 22, 2019",
"n1": "7",
"n2": "12",
"n3": "17",
"n4": "49",
"n5": "53",
"mb": "24"
}
],
"jackpot": "$208,000,000",
"next-jackpot":
{
"amount": "$226,000,000",
"date": "Tue, Nov 26, 2019"
}
}
}PHP Code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.collectapi.com/chancegame/usaMegaMillions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: apikey ",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
// Convert the JSON String into PHP Array
$array = json_decode($response, true);
// Extracting row by row
foreach($array as $row) {
$query .=
"INSERT INTO Meagamillions VALUES
('".$row["n5"]."'); ";
}
}Completely new to this, if you have any links to tutorials or helpful sites so I can read up that would be much appreciated!
8
Upvotes
12
u/MateusAzevedo Apr 04 '23
This is just a basic programming problem, there isn't anything special to it that requires a specific tutorial. For the database, it doesn't care where the data comes from.
Break the problem in small steps. First, how to insert data into the database? Read this article to learn about MySQLi, or this one for PDO, depending on which one you're using. The TL;DR: never concatenate variables in a SQL string, use prepared statements. This is very important* and a habit you want to learn as soon as possible.
With that figured out, how to read API responses? Well, that depend on each API, but you can ignore the database at first and focus on how to fetch the data you need. Take a look at the response example you provided, now add
var_dump($array)after thejson_decode()line, look at the data you have, its format. What I get back if I addvar_dump($array['result'])? What aboutvar_dump($array['result']['numbers'])? If you don't understand that, take a step back and learn about arrays.When all parts are figured out, then you'll be able glue everything together.
Given the example provided and the usage of
json_decode()with the second argument astrue, this likely what you need: