PHP脚本将新条目导出到SQL表并覆盖文件

时间:2013-02-07 18:24:29

标签: php sql pdo cron cron-task

我正在尝试创建一个每晚由cron作业运行的php脚本。

数据库保存联系表单中的条目。

这个想法是运行php脚本(通过cron)并让它从当天将数据库中的任何新条目导出到服务器上的csv文件中,每次都要覆盖该文件以进行内务处理。它只需要从那天起将条目导出到数据库。

这就是我现在所拥有的:

<?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);

?>

1 个答案:

答案 0 :(得分:0)

你的sql必须通过:

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