Sql to csv on php

Export Data to CSV File using PHP and MySQL

CSV (comma-separated values) is the most popular file format to store data in plain text for offline uses. Generally, a CSV file is used to import and export data for moving data between programs. Import and export data is the most used feature in the web application, and CSV file format is the best choice for that.

The import and export, both features are implemented easily with PHP in the web application. In the previous tutorial, we have discussed about Import CSV File Data into MySQL database using PHP. In this tutorial, we will show you how to export data from MySQL database to CSV file using PHP.

To demonstrate Export to CSV functionality, we will build an example script that will export member’s data from the MySQL database and save it in a CSV file using PHP.

  • Fetch data from the database using PHP and MySQL.
  • Create a CSV file in PHP and save data in it.
  • Export MySQL data and download it in a CSV file using PHP.

Create Database Table

To store the data, a table needs to be created in the database. The following SQL creates a members table with some basic fields in the MySQL database.

CREATE TABLE `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `gender` enum('Male','Female') COLLATE utf8_unicode_ci NOT NULL, `country` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php is used to connect the database. Specify the database host ( $dbHost ), username ( $dbUsername ), password ( $dbPassword ), and name ( $dbName ) as per your MySQL database credentials.

// Database configuration 
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) <
die(
"Connection failed: " . $db->connect_error);
>

Data List from MySQL Database (index.php)

Initially, all the member’s data is fetched from the database and listed in a tabular format.

  • An EXPORT button is placed at the top of the data list.
  • By clicking the Export button, the data is exported from the database and allow to download on a local drive as a CSV file.
 div class="col-md-12 head"> div class="float-right"> a href="exportData.php" class="btn btn-success">i class="dwn"> i> Export a> div> div> table class="table table-striped table-bordered"> thead class="thead-dark"> tr> th>#ID th> th>Name th> th>Email th> th>Gender th> th>Country th> th>Created th> th>Status th> tr> thead> tbody>  // Fetch records from database 
$result = $db->query("SELECT * FROM members ORDER BY id ASC");
if(
$result->num_rows > 0) <
while(
$row = $result->fetch_assoc()) <
?> tr> td> echo $row['id']; ?> td> td> echo $row['first_name'].' '.$row['last_name']; ?> td> td> echo $row['email']; ?> td> td> echo $row['gender']; ?> td> td> echo $row['country']; ?> td> td> echo $row['created']; ?> td> td> echo ($row['status'] == 1)?'Active':'Inactive'; ?> td> tr> > >else ?> tr>td colspan="7">No member(s) found. td> tr> > ?> tbody> table>

For this example script, the Bootstrap library is used to style the HTML table and buttons. So, include the Bootstrap CSS library and custom stylesheet file (if any).

 link rel="stylesheet" href="assets/bootstrap/bootstrap.min.css"> link rel="stylesheet" href="assets/css/style.css">

Export Data to CSV File using PHP (exportData.php)

The exportData.php file handles the data export and CSV file download process using PHP and MySQL.

  • Retrieve data from the MySQL database.
  • Create a file pointer using fopen() function.
  • Specify the header columns and put data into the CSV file.
  • Output each row of the data, format line as CSV, and write to file pointer.
  • Set Content-Type and Content-Disposition to force the browser to download the file rather than display it.
 
// Load the database configuration file
include_once 'dbConfig.php';

// Fetch records from database
$query = $db->query("SELECT * FROM members ORDER BY id ASC");

if(
$query->num_rows > 0) <
$delimiter = ",";
$filename = "members-data_" . date('Y-m-d') . ".csv";

// Create a file pointer
$f = fopen('php://memory', 'w');

// Set column headers
$fields = array('ID', 'FIRST NAME', 'LAST NAME', 'EMAIL', 'GENDER', 'COUNTRY', 'CREATED', 'STATUS');
fputcsv($f, $fields, $delimiter);

// Output each row of the data, format line as csv and write to file pointer
while($row = $query->fetch_assoc()) <
$status = ($row['status'] == 1)?'Active':'Inactive';
$lineData = array($row['id'], $row['first_name'], $row['last_name'], $row['email'], $row['gender'], $row['country'], $row['created'], $status);
fputcsv($f, $lineData, $delimiter);
>

// Move back to beginning of file
fseek($f, 0);

// Set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename color: #007700">. $filename . '";');

//output all remaining data on a file pointer
fpassthru($f);
>
exit;

?>

Conclusion

This example code provides an easy way to export data to CSV file in PHP. You can enhance or customize the functionality of this Export to CSV script as per your needs. If you want to implement this export functionality in client-side script, use JavaScript to do it – Export HTML Table Data to CSV using JavaScript

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

Читайте также:  Python время исполнения функции

If you have any questions about this script, submit it to our QA community — Ask Question

Источник

Простой импорт/экспорт в CSV для PHP & MySQL

В ходе разработки сервиса по расчете статистики по управлению запасами для интернет-магазинов возникла задача быстро организовать импорт/экспорт таблиц между разными MySQL серверами. Поскольку надо было сделать просто и прозрачно — оптимизация будет впереди — решил воспользоваться авторскими рекомендация из документации по MySQL 5.0.

В качестве формата обмена данными решил принять CSV именно по причине простоты реализации.

В итоге, получилось две функции

 function export_csv( $table, // Имя таблицы для экспорта $afields, // Массив строк - имен полей таблицы $filename, // Имя CSV файла для сохранения информации // (путь от корня web-сервера) $delim=',', // Разделитель полей в CSV файле $enclosed='"', // Кавычки для содержимого полей $escaped='\\', // Ставится перед специальными символами $lineend='\\r\\n') < // Чем заканчивать строку в файле CSV $q_export = "SELECT ".implode(',', $afields). " INTO OUTFILE '".$_SERVER['DOCUMENT_ROOT'].$filename."' ". "FIELDS TERMINATED BY '".$delim."' ENCLOSED BY '".$enclosed."' ". " ESCAPED BY '".$escaped."' ". "LINES TERMINATED BY '".$lineend."' ". "FROM ".$table ; // Если файл существует, при экспорте будет выдана ошибка if(file_exists($_SERVER['DOCUMENT_ROOT'].$filename)) unlink($_SERVER['DOCUMENT_ROOT'].$filename); return mysql_query($q_export); >
  • Файл можно создать на том же хосте, где расположен MySQL. Если ОС настроена с возможностью на сетевой диск с общим доступом, можно писать и на другой сервер.
  • Если поле в таблице равно NULL, в CSV файле будет выведено \N.
  • Для записи файла на локальный диск на сервере пользователю требуются права FILE не на уровне БД, а глобально на уровне сервера MySQL. Можно установить через PHPMyAdmin или запросом
GRANT FILE ON * . * TO 'username'@'localhost' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
 function import_csv( $table, // Имя таблицы для импорта $afields, // Массив строк - имен полей таблицы $filename, // Имя CSV файла, откуда берется информация // (путь от корня web-сервера) $delim=',', // Разделитель полей в CSV файле $enclosed='"', // Кавычки для содержимого полей $escaped='\\', // Ставится перед специальными символами $lineend='\\r\\n', // Чем заканчивается строка в файле CSV $hasheader=FALSE) < // Пропускать ли заголовок CSV if($hasheader) $ignore = "IGNORE 1 LINES "; else $ignore = ""; $q_import = "LOAD DATA INFILE '". $_SERVER['DOCUMENT_ROOT'].$filename."' INTO TABLE ".$table." ". "FIELDS TERMINATED BY '".$delim."' ENCLOSED BY '".$enclosed."' ". " ESCAPED BY '".$escaped."' ". "LINES TERMINATED BY '".$lineend."' ". $ignore. "(".implode(',', $afields).")" ; return mysql_query($q_import); >
  1. Короткие и очень быстрые функции, за счет того, что выполняются одним MySQL запросом.
  2. Довольно гибкая реализация — можно легко управлять множеством параметров, в том числе и списком полей
  3. Для экспорта: путем изменения списка полей в массиве полей

или использования подзапроса вместо имени таблицы (тогда в массиве будут указаны поля этого подзапроса) — например,

(select field1, field1 from table2) t
array("column1", "@dummy", "column2", "@dummy", "column3")

PS. На самом эти команды MySQL имеют более богатый синтаксис с дополнительными настройками, так что поле для улучшения этого кода ограничено только необходимостью и фантазией.

Источник

apocratus / export_csv.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/* vars for export */
// database record to be exported
$db_record = ‘XXXXXXXXX’;
// optional where query
$where = ‘WHERE 1 ORDER BY 1’;
// filename for export
$csv_filename = ‘db_export_’.date(‘Y-m-d’).’.csv’;
// database variables
$hostname = «localhost»;
$user = «XXXXXXXXX»;
$password = «XXXXXXXXX»;
$database = «XXXXXXXXX»;
// Database connecten voor alle services
mysql_connect($hostname, $user, $password)
or die(‘Could not connect: ‘ . mysql_error());
mysql_select_db($database)
or die (‘Could not select database ‘ . mysql_error());
// create var to be filled with export data
$csv_export = »;
// query to get data from database
$query = mysql_query(«SELECT * FROM «.$db_record.» «.$where);
$field = mysql_num_fields($query);
// create line with field names
for($i = 0; $i < $field; $i++)
$csv_export.= mysql_field_name($query,$i).’,’;
>
// newline (seems to work both on Linux & Windows servers)
$csv_export.= ‘
‘;
while($row = mysql_fetch_array($query))
// create line with field values
for($i = 0; $i < $field; $i++)
$csv_export.= ‘»‘.$row[mysql_field_name($query,$i)].'»,’;
>
$csv_export.= ‘
‘;
>
// Export the data and prompt a csv file for download
header(«Content-type: text/x-csv»);
header(«Content-Disposition: attachment; filename=».$csv_filename.»»);
echo($csv_export);
?>

Источник

Оцените статью