Created
April 8, 2019 20:45
-
-
Save pastranastevenaz/30d71fa2da30abe39e111e94bb651ae6 to your computer and use it in GitHub Desktop.
Export a database table to a csv and prompt for download
This file contains hidden or 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
| <?php | |
| // The name of the table | |
| $db_record = ''; | |
| // optional where query | |
| $where = 'WHERE 1 ORDER BY 1'; | |
| $csv_filename = 'db_export_'.$db_record.'_'.date('Y-m-d').'.csv'; | |
| $hostname = ""; | |
| $user = ""; | |
| $password = ""; | |
| $database = ""; | |
| $port = ; | |
| $conn = mysqli_connect($hostname, $user, $password, $database, $port); | |
| if (mysqli_connect_errno()) { | |
| die("Failed to connect to MySQL: " . mysqli_connect_error()); | |
| } | |
| $csv_export = ''; | |
| $query = mysqli_query($conn, "SELECT * FROM ".$db_record." ".$where); | |
| $field = mysqli_field_count($conn); | |
| for($i = 0; $i < $field; $i++) { | |
| $csv_export.= mysqli_fetch_field_direct($query, $i)->name.';'; | |
| } | |
| $csv_export.= ' | |
| '; | |
| while($row = mysqli_fetch_array($query)) { | |
| // create line with field values | |
| for($i = 0; $i < $field; $i++) { | |
| $csv_export.= '"'.$row[mysqli_fetch_field_direct($query, $i)->name].'";'; | |
| } | |
| $csv_export.= ' | |
| '; | |
| } | |
| header("Content-type: text/x-csv"); | |
| header("Content-Disposition: attachment; filename=".$csv_filename.""); | |
| echo($csv_export); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment