PHP 7 Script to Export MySQL Table to CSV File in Browser Using Javascript Full Project For Beginners

  • Post author:
  • Post category:PHP
  • Post comments:0 Comments

 

 

Welcome folks today in this blog post we will be exporting ysql table to csv file in browser using php and javascript. All the full source code of the application is shown below.

 

 

 

 

Get Started

 

 

 

 

In order to get started you need to make an index.php file and copy paste the following code

 

 

 

index.php

 

 

 

<?php
extract($_POST);
if(isset($save))
{
// Database Connection
$host="localhost";
$uname="root";
$pass="";
$database = "demo"; 

$connection=mysql_connect($host,$uname,$pass); 

echo mysql_error();

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");  
$result=mysql_select_db($database)
or die("database cannot be selected <br>");

    
// Fetch Record from Database

$output         = "";
$table          = "users_csv"; // Enter Your Table Name(table from previous tutorial)
$sql            = mysql_query("select * from $table");
$columns_total  = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++)
 {
    $heading    =   mysql_field_name($sql, $i);
    $output     .= '"'.$heading.'",';
}
$output .="n";

echo $output;
// Get Records from the table

while ($row = mysql_fetch_array($sql))
{
for ($i = 0; $i < $columns_total; $i++) 
{
$output .='"'.$row["$i"].'",';
}
$output .="n";
}

echo $output;
// Download the file

$filename =  "myFile.csv";
//header('Content-type: application/csv');
//header('Content-Disposition: attachment; filename='.$filename);

//echo $output;
//exit;


}   
?>

<form method="post">
    <input type="submit" value="Export Mysql In CSV" name="save"/>
</form>

Leave a Reply