Export Custom Table to CSV
-
I’ve got a custom database table that I’m storing information to and I need to export selected rows(id’s) to a csv file. Currently I have added a an option for “Export” to my bulk actions and it will export the entire table to a CSV file, but I need to only export entries that have been checked for bulk option. Here is the code I have so far.
function process_bulk_action() { global $wpdb; $bp_table_name = $wpdb->prefix . 'custom_table'; // do not forget about tables prefix ?> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('<option>').val('export').text('<?php _e('Export')?>').appendTo("select[name='action']"); jQuery('<option>').val('export').text('<?php _e('Export')?>').appendTo("select[name='action2']"); }); </script> <?php if ('export' === $this->current_action()) { ob_end_clean(); $sql = $wpdb->get_results( "SELECT * FROM $bp_table_name"); if (!$sql) { die('Invalid query: ' . mysql_error()); } // Get The Field Name $output .= 'Exhibitor Company'. ','; $output .= 'Exhibitor Representative'. ','; $output .= 'Position Title'. ','; $output .= 'Mailing Address'. ','; $output .= 'City'. ','; $output .= 'State'. ','; $output .= 'Zip'. ','; $output .= 'Website'. ','; $output .= 'Office Phone'. ','; $output .= 'Cell Phone'. ','; $output .= 'Email'. ','; $output .= 'Backup Email'. ','; $output .= 'Products/Services'. ','; $output .= 'Same Booth Space'. ','; $output .= 'Booth Numbers'. ','; $output .= 'Convention Center'. ','; $output .= 'Expo Halls'. ','; $output .="\n"; // Get Records from the table foreach ($sql as $row) { $output .="\n"; $output .='"'.$row->exhibitor_company.'",'; $output .='"'.$row->exhibitor_rep.'",'; $output .='"'.$row->title.'",'; $output .='"'.$row->address.'",'; $output .='"'.$row->city.'",'; $output .='"'.$row->state.'",'; $output .='"'.$row->zip.'",'; $output .='"'.$row->website.'",'; $output .='"'.$row->office_phone.'",'; $output .='"'.$row->cell.'",'; $output .='"'.$row->email.'",'; $output .='"'.$row->backup_email.'",'; $output .='"'.$row->products_services.'",'; $output .='"'.$row->same_space.'",'; $output .='"'.$row->booth_numbers.'",'; $output .='"'.$row->convention_center.'",'; $output .='"'.$row->expo_halls.'",'; } $output .="\n"; // Download the file $file = "custom_table"; $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); echo $output; exit; } $entry_id = ( is_array( $_REQUEST['id'] ) ) ? $_REQUEST['id'] : array( $_REQUEST['id'] ); if ( 'delete' === $this->current_action() ) { global $wpdb; foreach ( $entry_id as $id ) { $id = absint( $id ); $wpdb->query( "DELETE FROM $bp_table_name WHERE id = $id" ); } } }
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- The topic ‘Export Custom Table to CSV’ is closed to new replies.