How to delete the first ten records from a table when reaching a certain number of Rows?

Asked

Viewed 455 times

0

Good evening, I have an SQL table in which I will put movie recommendations by users, but I want when it reaches a total of records in this table, it deletes the older records.

My code is like this:

$sql = "INSERT INTO filmes_rec (filmes)
        VALUES ('$recomendacao')";

if($link->query($sql) === TRUE) {
    echo 'Obrigado por compartilhar seu gosto com a gente, você recomendou:<br>'; 
    echo '<p class="strong"><strong>';
    echo $recomendacao;
    echo '</strong></p>';
} else {
    echo "Error creating new record";
}

2 answers

2

DELETE FROM filmes_rec ORDER BY nome_da_tabela ASC LIMIT 0, 10

in "table name" put the name of the table that will be using in an organizational way, for example the column that contains the date of the records so it will erase the 10 but old.

1


It is not possible to put a value of lines in the table, so you need to create a method for this.

You can give COUNT in the table and, if the value is greater than the maximum, DELETE older (using ID, date or what allows such comparison).

$sql = INSERT INTO filmes_rec (filmes)
            VALUES ('$recomendacao');

if($link->query($sql) === TRUE) {

   $count = SELECT COUNT(*)
              FROM filmes_rec
             WHERE usuario_id = x //se você tiver um identificador que precisa usar no count

   if($link->query($count) > n) {
     DELETE FROM filmes_rec
           WHERE id > n;
   }

    echo 'Obrigado por compartilhar seu gosto com a gente, você recomendou:<br>'; 
    echo '<p class="strong"><strong>';
    echo $recomendacao;
    echo '</strong></p>';
} else {
    echo "Error creating new record";
}

This way I use the same pattern that you are using, but it is possible to also do this with a PROCEDURE. Instead of running in the PHP script it will run in Mysql and is less likely to give problem by changing code or things like that (the method will be linked to DB).

  • DBMS was not specified but other solutions would be TRIGGER or a scheduling process (jog , Event etc) but these solutions depend on BD.

  • I don’t want to delimit lines in the database, I just want to do that when it gets to a specific number of lines, it deletes some records from the table.

  • I don’t understand. You need that when the table reaches 51 lines, it erases the oldest value to get only the 50 newest ones is not?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.