How to add daily stock price history col in mysql table in php using cron job?

by bernice_zulauf , in category: Technical Analysis , a month ago

How to add daily stock price history col in mysql table in php using cron job?

Facebook Twitter LinkedIn Whatsapp

1 answer

Member

by skyla , a month ago

@bernice_zulauf 

To add daily stock price history in a MySQL table using PHP and a cron job, you can follow these steps:

  1. Create a table in your MySQL database to store the stock price history. This table should have columns for the stock symbol, the date, and the price. CREATE TABLE stock_price ( id INT AUTO_INCREMENT PRIMARY KEY, symbol VARCHAR(10) NOT NULL, date DATE NOT NULL, price DECIMAL(10, 2) NOT NULL );
  2. Create a PHP script that fetches the stock price data from an API or any other source. ://api.example.com/stocks'; // Fetch the stock price data $data = file_get_contents($apiUrl); $stocks = json_decode($data, true); // Insert the stock price data into the database $pdo = new PDO('mysql:host=localhost;dbname=your_database_name', 'your_username', 'your_password'); foreach ($stocks as $stock) { $symbol = $stock['symbol']; $date = $stock['date']; $price = $stock['price']; $query = "INSERT INTO stock_price (symbol, date, price) VALUES (?, ?, ?)"; $stmt = $pdo->prepare($query); $stmt->execute([$symbol, $date, $price]); } ?>
  3. Save the PHP script on your server, for example, as update_stock_price.php.
  4. Configure a cron job to execute the PHP script daily. Edit your crontab file using the command crontab -e, and add the following line to run the PHP script every day at midnight: 0 0 * * * php /path/to/update_stock_price.php Make sure to replace /path/to/update_stock_price.php with the actual path to your script.


Now, the cron job will run the PHP script daily at midnight, fetching the stock price data and inserting it into the MySQL table stock_price.