简体   繁体   中英

How to create a excel csv which contains a specific table in my php mysql database

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM