Export CSV file from MySQL Database in PHP

[code]<?php


// Connection variables
$host = "server"; // MySQL host name eg. localhost
$user = "user"; // MySQL user. eg. root ( if your on localserver)
$password = "password"; // MySQL user password (if password is not set for your root user then keep it empty )
$database = "database"; // MySQL Database name

// Connect to MySQL Database
$con = new mysqli($host, $user, $password, $database);

// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}

// Database Connection
// get Users
$query = "SELECT * FROM contacts";
if (!$result = mysqli_query($con, $query)) {
exit(mysqli_error($con));
}

$users = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$users[] = $row;
}

}

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=contacts.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('id', 'fname', 'lname', 'phone','phonebook'));

if (count($users) > 0) {

foreach ($users as $row) {
fputcsv($output, $row);
}

}
?>[/code]

Download

Leave a Reply

Your email address will not be published. Required fields are marked *