Saturday, March 29, 2014

Export table values from MYSQL to CSV Using PHP

In this article we will discuss about export table values from MYSQL to CSV.

Let's have look.


Change values as per your requirement.

conn.php

<?php

        //config file
      
        define('host','localhost');/*Hostname*/
       
        define('username','root');/*Username*/
       
        define('password','');/*Password*/
       
        define('database','register');/*Database*/
       
        $conn=mysql_connect(host,username,password) or die(error);
       
        $db=mysql_select_db(register,$conn);
       
        ?>

sqltocsv.php

<?php

include("conn.php"); //Database config file

$result = mysql_query("select * from reg");/*edit as per your requirement*/

if (mysql_num_rows($result) > 0)

{

$csv="FIRSTNAME".","."LASTNAME".","."GENDER".","."MONTH".","."COUNTRY".","."EMAIL".","."PASSWORD".","."PASSWORD1".","."EMAIL1".","."SECERT1".","."ANSWER".","."SECRET2".","."ANSWER1"."\n";

while ($row = mysql_fetch_array($result))

{

$csv.= $row['firstname'].",".$row['lastname'].",".$row['gender'].",".$row['month'].",".$row['country'].",".$row['email']

.",".$row['password'].",".$row['password1'].",".$row['email1'].",".$row['secert1'].",".$row['answer'].",".$row['secret2'].",".$row['answer1'];

$csv.= "\n";

}

}

//print $csv;

$filename = date("Y-m-d/H-i",time());

header("Content-type: application/vnd.ms-excel");

header( "Content-disposition: filename=".$filename.".csv");

print $csv;

exit;

?>

Please share your comments and feedback.Thanks.Please subscribe my updates via email.

No comments:

Post a Comment