PHP MYSQL

HOW TO EXPORT MYSQL TO CSV IN PHP

DUMMY USER TABLE user_id | INT(11) | PRIMARY KEY user_email | VARCHAR(255) user_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 (PART 1)

02

CONNECT TO DATABASE $dbHost = 'localhost'; $dbName = 'test'; $dbChar = 'utf8'; $dbUser = 'root'; $dbPass = ''; $pdo = new PDO(   "mysql:host=$dbHost;dbname=".   $dbName;charset=$dbChar",   $dbUser, $dbPass,   [PDO::ATTR_ERRMODE =>    PDO::ERRMODE_EXCEPTION] );

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

PHP EXPORT CSV (PART 2)

03

GET USERS & OUTPUT  $stmt = $pdo->prepare("SELECT *  FROM `users`"); $stmt->execute(); while ($row = $stmt->fetch   (PDO::FETCH_NAMED)) {   echo implode(",", [$row['user_id'],     $row['user_email'],    $row['user_name']]);    echo "\r\n"; }

Manually set in the headers.

PHP EXPORT CSV (PART 3)

04