Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*** mysql hostname ***/
- $hostname = 'localhost';
- $dbname = 'dbname';
- /*** mysql username ***/
- $username = 'username';
- /*** mysql password ***/
- $password = 'password';
- try {
- $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
- $tablename = 'table';
- $sql = 'SHOW COLUMNS FROM `'.$tablename.'`';
- $stmt = $dbh->query($sql);
- $stmt->execute();
- while($row = $stmt->fetch(PDO::FETCH_ASSOC))
- {
- array_push($fields, $row['Field']);
- }
- array_push($csv, $fields);
- $sql = 'SELECT * FROM `'.$tablename.'`';
- $stmt = $dbh->query($sql);
- $stmt->execute();
- $csv = array();
- while($row = $stmt->fetch(PDO::FETCH_NUM))
- {
- array_push($csv, $row);
- }
- $fp = fopen('file.csv', 'w');
- foreach ($csv as $row) {
- fputcsv($fp, $row);
- }
- fclose($fp);
- header("Content-type: application/csv");
- header("Content-Disposition: attachment; filename=export.csv");
- header("Pragma: no-cache");
- header("Expires: 0");
- readfile('file.csv');
- $dbh = null;
- } catch(PDOException $e) {
- echo $e->getMessage();
- }
Add Comment
Please, Sign In to add comment