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

如何在我的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.

我想为我的网站制作一个程序,该程序将在我的数据库中输入数据的csv报告。 问题是我不知道怎么做。 我知道这可能是由于我的搜索,但所有这些都没有真正愚蠢到足以让我理解。 有人可以请我推进正确的方向吗? p>

  Date | 参赛作品
 2016 |  99条记录
 2017年|  50条记录
  code>  pre> 
 
 

我希望在excel文件中按顺序显示列名和行。 p> DIV>

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, ";");
}