Search code examples
phpmysqlsql-delete

how can i delete all the records in my mysql table automatically using php?


i am trying to create some code to delete all the records in my mysql table automatically, i have done it in an older projet, but in this case, when i use the exact same script it does not work. i am trying to make it delete after 60 seconds just for testing but i must be doing something wrong.

all the help is much apreciated

my code:

<?php
    function apaga(){

     $dbconn = mysqli_connect("localhost", "root", "", "fct");

     if($dbconn->connect_error){

         die("Falha ao conectar ao servidor: ".$dbconn->connect_erro);

     }

    $queryselect=$dbconn->query("SELECT * FROM mostra1 ")or die(mysqli_error($dbconn));

    while($row=$queryselect->fetch_assoc()){

        $id=$row['id'];

    $sql= "DELETE * FROM mostra1 WHERE `data` < (NOW() - INTERVAL 60 SECONDS)";


    mysqli_query($dbconn,$sql);

     }
    }

    apaga();

    ?>

Solution

  • Try this mate :)

    <?php
      
    	function apaga(){
         $conexao = mysqli_connect("localhost", "root", "", "fct");
    
        if($conexao->connect_error){
    
    	 die("Falha ao conectar ao servidor: ".$conexao->connect_erro);
    
     }
    
        $queryselect=$conexao->query("SELECT * FROM mostra1")or die(mysqli_error($conexao));;
    
       while($row=$queryselect->fetch_assoc()){
    
          $id=$row['id'];
    
          $sql= "DELETE FROM mostra1 WHERE data < (NOW() - INTERVAL 1 MINUTE)";
    
          mysqli_query($conexao,$sql);
    
      }
    
    
    }
    
    
    apaga();
    
    ?>