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);


Complete PHP Code to Export MySQL Data to CSV File

    //simple mysql database connection using php details
    $host = "localhost";
    $username = "root";
    $password = "db**898**";
    $dbname = "products";

    // simple data open connection to mysql database using php
    $connection = mysqli_connect($host, $username, $password, $dbname) or die("data Connection Error " . mysqli_error($connection));
    //here query using php to fetch mysql table rows data
    $sql_query = "select * from products";
    $result = mysqli_query($connection, $sql_query) or die("Database table Selection Error " . mysqli_error($connection));

    $fp = fopen('products.csv', 'w');

    while($row = mysqli_fetch_assoc($result))
        fputcsv($fp, $row);

    //your file close the db (database) connection