dougutuo9879 2019-04-05 12:59
浏览 60
已采纳

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

Yes, as my question asks, I need to delete records and the same records that I deleted save them dynamically in a file

I can only view or delete them

<?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 } ?>

understanding this process I am able to delete data in my db but keep a local copy just in case

  • 写回答

2条回答 默认 最新

  • douwei8911 2019-04-05 13:16
    关注

    You could save these results in a JSON array.

    <?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 );
    
    ?>
    

    for example, if your table looks like this:

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

    your backup file will look like this:

    [{"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"}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办