Export data mysql table to csv file using PHP

Export data mysql table to csv file using PHP

Welcome to the In Pakainfo.com website! You will Step By Step learn web programming, easy and very fun. This website allmost provides you with a complete web programming tutorial presented in an easy-to-follow manner. Each web programming tutorial has all the practical examples with web programming script and screenshots available.In My Export data mysql table to csv file using PHP

How to Import and Export CSV Files Using PHP and MySQL

// download invoice csv sheet
if ($action == 'download_csv'){

	header("Content-type: text/csv"); 

	// any output any to connection error display
	if ($mysqli->connect_error) {
		die('Error : ('.$mysqli->connect_errno .') '. $mysqli->connect_error);
	}
 
    $fname = 'invoice-data-'.date('d-m-Y').'.csv';   // simple file name
    $fileuserpath = 'downloads/'.$fname; // here file path put

	$file = fopen($fileuserpath, "w"); // php file handling to open a file in write mode
    chmod($fileuserpath, 0777);    //php file handling to set the file permission

    $query_table_columns = "SELECT * 
									FROM products i
									JOIN users c
									ON c.productname = i.productname
									WHERE i.productname = c.productname
									ORDER BY i.productname";

    if ($result_column = mysqli_query($mysqli, $query_table_columns)) {

    	// fetch the table fields data in mysql
        while ($column_data = $result_column->fetch_row()) {

            $collumdata = array();
            foreach($column_data as $data) {
                $collumdata[] = $data;
            }

            // her Format array like as CSV data and write to all file pointer
            fputcsv($file, $collumdata, ",", '"');
        }

	}

 }

$result_data = mysqli_query($con, 'SELECT * FROM productmst');
$row_data = mysqli_fetch_array($result_data, MYSQLI_ASSOC);

$fipeopen = fopen('myfile.csv', 'w');

foreach ($row_data as $val) {
    fputcsv($fipeopen, $val);
}

fclose($fipeopen);

Complete PHP Code to Export MySQL Data to CSV File


Leave a Comment