从数据库中删除记录并将其保存到文件-PHP

时间:2019-04-05 12:59:37

标签: php mysql sql

是的,正如我的问题所问,我需要删除记录,删除的记录也要动态地保存在文件中

我只能查看或删除它们

<?php

    session_start();

    include 'connessione.php';

    $id = $_SESSION['id'];

    $query_string = "SELECT * FROM utenti ORDER BY id DESC LIMIT 50";
    $query = mysqli_query($connessione, $query_string);

    ?>
    <?php

    while($row = mysqli_fetch_assoc($query)){ ?>

    <?php echo $row['id'] ;?>

    <?php } ?>

了解此过程后,我可以删除数据库中的数据,但保留本地副本以防万一

2 个答案:

答案 0 :(得分:1)

是的,您可以将它们保存在文件中,然后再删除记录。

答案 1 :(得分:0)

您可以将这些结果保存在JSON数组中。

<?php

    //Start the session
    session_start();

    //Include connection
    include 'connessione.php';

    //Get user ID
    $id = $_SESSION['id'];

    //Query to get stuff from database
    $query_string = "SELECT * FROM utenti ORDER BY id DESC LIMIT 50";
    $query = mysqli_query($connessione, $query_string);

    //Get results
    $results = mysqli_fetch_assoc($query);

    //Make that into a JSON array
    $results = json_encode( $results );

    //Put those results in a file (create if file not exist)
    $fileName = 'backup_file_' . time() . '.txt';
    $file = fopen( $fileName , 'a'  );
    fwrite( $file, $results );
    fclose( $file );

    //Delete the rows that you just backed up
    $query_delete = "DELETE FROM utenti ORDER BY id DESC LIMIT 50";
    mysqli_query( $connessione, $query_delete );

?>

例如,如果您的表如下所示:

| id | name | email_address |
|----+------+---------------|
| 1  | dave | dave@test.com |
| 2  | emma | emma@test.com |
| 3  | mark | mark@test.com |
+----+------+---------------+

您的备份文件将如下所示:

[{"id":1,"name":"dave","email_address":"dave@test.com"},{"id":2,"name":"emma","email_address":"emma@test.com"},{"id":3,"name":"mark","email_address":"mark@test.com"}]