Search code examples
phpsqlpdocroncron-task

PHP script export new entries to SQL table and overwrite file


I am trying to create a php script that will be run by a cron job on a nightly basis.

The database holds entries from a contact form.

The idea is to run the php script (via cron) and have it export any new entries from the database from that day into a csv file on the server, overwriting that file each time for housekeeping. It needs to only export the entries to the database from that day.

Here is what I have at the moment:

<?php

// Connect and query the database for the users
$conn = new PDO("mysql:host=localhost;dbname=dbname", 'username', 'password');
$sql = "SELECT * FROM enquiries ORDER BY firstname";
$results = $conn->query($sql);

// Pick a filename and destination directory for the file
// Remember that the folder where you want to write the file has to be writable
//$filename = "/tmp/db_user_export_".time().".csv";
$filename = "/home/domain/public_html/csv/db_user_export.csv";

// Actually create the file
// The w+ parameter will wipe out and overwrite any existing file with the same name
$handle = fopen($filename, 'wb');

// Write the spreadsheet column titles / labels
fputcsv($handle, array('FirstName','Email'));

// Write all the user records to the spreadsheet
foreach($results as $row)
{
    fputcsv($handle, array($row['firstname'], $row['email']));
}

// Finish writing the file
fclose($handle);

?>

Solution

  • Your sql must by:

    SELECT * FROM enquiries where DATE(DateField) = CURDATE() ORDER BY firstname