Save data to MySQL Database from an API every 3 hours

Hi,

I am currently downloading data from an API using AJAX javascript.

So - basically it creates a “console.log” and then I use Javascript to enter the data on the website but this is live.

What I need to do (to minimise API requests) is NOT request the data live. Instead I need to download the data from the API every 3 hours to a MySQL database. Can I do this with my current console.log coding in Javascript?

How do I request and save the data to MySQL database every 3 hours. I think it is known as caching?

I know how to display data from MYSQL once it is there.

Kind regards,

Matt.

You probably want a cronjob to update your database every 3 hours.

1 Like

i have searched google for ‘cronjob and mysql’ and it just talks about ‘backup databases’ not creating the data for the database using an API?

What should I be searching for instead?

A cron job can be any script for whatever purpose that runs at a regular interval that you set.
You can set one up from Control Panel. You just need to write a script that does what you want to do, then set it as a cron job.

Ah. I think I missed the point that you were accessing the API via Ajax / JS. Cron is a server tool so a cronjob will be written in a server-side script such as PHP or Python.

Sam,

2 questions:

  1. Can the script be Javascript and if so how to I “write to the database” rather than write to the html document?

  2. When you say in Control Panel - with GoDaddy do you mean CPanel in my hosting account?

Thanks.

Not sure, all my cron jobs are php, which would probably be best for this.
Edit
Though as Gandalf says, it’s run by the server, so it should be server side.

Yes, look for cron job there.

Sam,

My current ‘live’ AJAX coding says “type: get”. Would this need to change for use with PHP.

I am unsure how to request data using PHP. Do you have an example code that I could view to get an idea how it would work?

Thanks,

Matt.

I’m not sure exactly what you are doing, is it a file you are getting from somewhere? possibly this?

$filedata = file_get_contents($url); 

I am using a JSON API - this page might help me?

I have found the below code to download API data - my question now is ‘how to I create a MySQL table to display the output JSON’?

<?php // your-script.php $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, 'http://dvcticker.bugs3.com/json-data.php'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $data = curl_exec($ch); curl_close($ch); // connect to database and save $data to your table ?>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.