PHP MYSQL

EXPORT MYSQL TO CSV IN PHP

(quick guide & example)

DUMMY USER TABLE id | BIGINT(11) | PRIMARY KEY email | VARCHAR(255) name | VARCHAR(255)

DUMMY USERS 1| job@doe.com | Job Doe 2 | jon@doe.com | Jon Doe 3 | joy@doe.com | Joy Doe

DUMMY TABLE & DATA

01

PHP EXPORT CSV (A)

02

CONNECT TO DATABASE $pdo = new PDO("mysql:host=HOST; dbname=NAME;charset=utf8", USER, PASSWORD);

HTTP "SAVE AS CSV" HEADERS header("Content-Type: application/ octet-stream"); header("Content-Transfer-Encoding:  Binary"); header("Content-disposition:  attachment; filename=\"demo.csv\"");

GET USERS & OUTPUT  $out = fopen("php://output", "w"); $stmt = $pdo->prepare("SELECT * FROM `users`"); $stmt->execute(); while ($row = $stmt->fetch())   { fputcsv($out, $row); } fclose($out);

PHP EXPORT CSV (B)

03