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条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题