Deleting data automatically after a certain time

7

Example:

I have a table with three fields: id int pk, varchar name, int category

The category field can receive 2 values: 1 and 2; By default always when a data is entered it will have a category 1.

What I want is this. When a data is entered, it has up to 10 days to be changed to 2. Otherwise, it will be deleted.

Is there any way I can do this?

Thank you!

    
asked by anonymous 27.11.2015 / 20:32

2 answers

5

Use create-event.

I'd rather be like :

Create a procedure:

CREATE PROCEDURE delete_rows_links()
    BEGIN
       DELETE FROM minhatabela WHERE categoria = 1 AND data < CURRENT_DATE()-10;
     END

CREATE EVENT myevent
    ON SCHEDULE EVERY 5 SECOND (vc escolhe)
    DO
      CALL delete_rows_links();

The link has more definitions where you can learn more.

    
27.11.2015 / 20:36
3

Record the start and end date that he entered the category and leave the server scheduled to check if it is between the 10 day period, if it has not passed it it removes the data.

You can schedule a script with crontab on the server as follows, it will ping your script according to the time period you program, and in this script, you check the date:

Will run:

  • Once a year: 0 0 1 1 * .
  • Every month: 0 0 1 * * .
  • Once a week: 0 0 * * 0 .
  • Once a day: 0 0 * * * .
  • Every hour: 0 * * * * .

0 0 * * 0 php /path/complete/do/seuscript.php

Your script:

<?php

$mysqli = new mysqli("localhost", "root", "senha", "banco");

/* verifica se está conectado */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "DELETE FROM evento
          WHERE status =1
          AND now() NOT BETWEEN data_inicial AND data_final";
$stmt = $mysqli->prepare($query);

And to save the 10 day period:

$mysqli = new mysqli("localhost", "root", "senha", "banco");

/* verifica se está conectado */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$nome = $_POST['nome'];
$dataInicial = new DateTime();
$dataFinal   = new DateTime('+10 days');


$query = "INSERT INTO evento (nome, categoria, status, data_inicial, data_final) VALUES(?,null, 1, ?, ?) ";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $nome, $dataInicial, $dataFinal);
    
27.11.2015 / 21:35