export to csv table data in php

 <?php


// Database Connection

error_reporting(E_ALL);

error_reporting(0);

$host="localhost";

$uname="root";

$pass="";

$database = "test";


$connection=mysqli_connect($host,$uname,$pass,$database); 


// 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 = "employee"; // Enter Your Table Name

$sql = mysqli_query($connection,"select * from $table");

$columns_total = mysqli_num_rows($sql);


// Get The Field Name




while ($property = mysqli_fetch_field($sql)) {

    //echo $property->name;

    $output .= '"'.$property->name.'",';

}




// for ($i = 0; $i < $columns_total; $i++) {

// $heading = mysqli_fetch_field($sql);

// $output .= '"'.$heading.'",';

// }

$output .="\n";


// Get Records from the table


while ($row = mysqli_fetch_array($sql)) {

for ($i = 0; $i < $columns_total; $i++) {




$output .='" '.$row["$i"].' ",';

}

$output .="\n";

}


// Download the file


$filename =  "myFile.csv";

header('Content-type: application/csv');

header('Content-Disposition: attachment; filename='.$filename);


echo $output;

exit;

?>


Post a Comment

0 Comments