Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /* vars for export */
- // database record to be exported
- $db_record = 'foo';
- // optional where query
- $where = '';
- // filename for export
- $csv_filename = 'dbExport' .$db_record. '_' .date('m-d-Y').'.csv';
- // database variables
- $hostname = "localhost";
- $user = "XXXXX";
- $password = "XXXXX";
- $database = "XXXXX";
- $port = 3306;
- $conn = mysqli_connect($hostname, $user, $password, $database, $port);
- if (mysqli_connect_errno()) {
- die("Failed to connect to MySQL: " . mysqli_connect_error());
- }
- // create empty variable to be filled with export data
- $csv_export = "\xEF\xBB\xBF";
- // query to get data from database
- $query = mysqli_query($conn, "SELECT * FROM ".$db_record." ".$where);
- $field = mysqli_field_count($conn);
- // create line with field names
- for($i = 0; $i < $field; $i++) {
- $csv_export.= '"' . mysqli_fetch_field_direct($query, $i)->name . '"';
- if($i < ($field-1)){
- $csv_export.=',';
- }
- }
- // newline (seems to work both on Linux & Windows servers)
- $csv_export.= "\r\n";
- // loop through database query and fill export variable
- while($row = mysqli_fetch_array($query)) {
- // create line with field values
- for($i = 0; $i < $field; $i++) {
- $csv_export.= '"'.addslashes($row[mysqli_fetch_field_direct($query, $i)->name]).'"';
- if($i < ($field-1)){
- $csv_export.=',';
- }
- }
- $csv_export.= "\r\n";
- }
- // Export the data to a location on the server
- $dir = '/directory/you/want/to/write/to/goes/here' . $csv_filename;
- $handle = fopen($dir, 'w+');
- fwrite($handle, $csv_export);
- fclose($handle);
- ?>
Add Comment
Please, Sign In to add comment