0

How do make auto delete SQL table records on every month. For example: we have 3 columns. DATE, NAME and ADDRESS. So when daily entry to that table , it stores in table. I need to delete all these records save in another table and make it empty in every month.

4

1 回答 1

1

您需要为此设置一个 cronjob,例如:

#this will run every 1'st of the month at 00:00 AM
0 0 1 * * /usr/bin/php -f /path/to/script.php

script.php

<?php
    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

    $monthYear = date('mY', strtotime('-1 day')); // last month
    $table = 'addresses'; // current table name
    $newTable = $table.'_'.$monthYear; // new table name oldTable_monthYear

    try {
        $db->beginTransaction();
        $query = $db->query("CREATE TABLE `".$newTable ."` LIKE `".$table ."`"); // create new table like old one
        $query = $db->query("INSERT INTO `".$newTable ."` SELECT * FROM `".$table ."`"); // insert values in new table
        $query = $db->query("TRUNCATE TABLE `".$table ."`"); // truncate old table
    } catch(PDOException $ex) {
        $db->rollBack(); // something went wrong, rollback all actions
        echo $ex->getMessage(); // output error
    }
?> 
于 2012-09-17T13:34:42.643 回答