PHP MYSQL

HOW TO EXPORT MYSQL TO CSV IN PHP

DUMMY USER TABLE id | INT(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, [   PDO::ATTR_DEFAULT_FETCH_MODE   => PDO::FETCH_NAMED ]);

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

PHP EXPORT CSV (B)

03

GET USERS & OUTPUT  $stmt = $pdo->prepare("SELECT * FROM `users`"); $stmt->execute(); while ($r = $stmt->fetch()) {   echo implode(",", [$r["id"], $r["email"],   $r["name"]]);    echo "\r\n"; }

PHP EXPORT CSV (C)

04