dongqing5575 2017-03-08 09:17
浏览 69
已采纳

如何在我的php mysql数据库中创建一个包含特定表的excel csv

I would like to make a program for my website that will make a csv report of the data entered in my database. The problem is that I don't have a clue how. I know it's possible due to my searching but all of them did not really dumb it down to be enough for me to understand. Can someone please push me into the right direction?

    Date | Entries
    2016 | 99 Records
    2017 | 50 Records

I'd like for this to show in the excel file along with the column name and the rows in order.

  • 写回答

1条回答 默认 最新

  • dpj0015 2017-03-08 09:29
    关注

    First make a connection with your database:

    $databaseName     = ''; 
    $databaseHostname = 'localhost'
    $databaseUsername = ''; 
    $databasePassword = ''; 
    
    $pdo = new PDO(
    'mysql:host=' . $databaseHostname . ';dbname=' . $databaseName,
    $databaseUsername,
    $databasePassword);
    

    Now get all data from the table

    $tableName = 'test';
    $statement = $pdo->prepare('SELECT * FROM ' . $tableName);
    $results = $statement->fetchAll(PDO::FETCH_ASSOC);
    

    Now create a csv file

    $fileName = 'test.csv';
    $csvFile = new SplFileObject($fileName, 'w');
    

    And add the data to the csv file.

    foreach ($results as $row) {
        $csvFile->fputcsv($row, ";");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi