Wednesday, August 21, 2013

Importing data from CSV file to mysql database using php..........


<?php
//database connection details
$host = "localhost";
$user = "root"; //user of mysql
$password = "";
$database = "sample"; //database name
try {
if (mysql_connect($host, $user, $password)) {
     mysql_select_db ("sample");
}
else {
throw new Exception('Unable to connect');
}
}
catch(Exception $e) {
echo $e->getMessage();
}
   
           define('CSV_PATH','C:/wamp/www/');   // path where your CSV file is located
          $csv_file = CSV_PATH . "export.csv"; // Name of your CSV file
       
         if (($getfile = fopen($csv_file, "r")) !== FALSE) {
            $data = fgetcsv($getfile, 1000, ",");
           while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
                $num = count($data);
                for ($c=0; $c < $num; $c++) {
                     $result = $data;
                     $str = implode(",", $result);
                     $slice = explode(",", $str);        
                     $col1 = $slice[0];
                     $col2 = $slice[1];
     $col3 = $slice[2];

                    // SQL Query to insert data into DataBase
                     $query = "INSERT INTO csv_to_db VALUES('".$col1."','".$col2."','".$col3."')";
                   // csv file consists of 3 fields, hence using 3 columns(i.e., col1,col2,col3)
                     $s=mysql_query($query);
                 }
       }
}
echo "File data successfully imported to database!!";
mysql_close();
?>

~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$

Tuesday, August 20, 2013

Simple way of Exporting database to Csv format using php..

For Php Newbie.............

simple way of Exporting Data in Mysql Table To Csv Format:

<?php
$host = "localhost"; //hostname
$user = "root"; //admin
$password = ""; //password of Mysql
$database = "vino"; //database name
try {
if (mysql_connect($host, $user, $password)) {
dbconnection();
}
else {
throw new Exception('Unable to connect');
}
}

catch(Exception $e) {
echo $e->getMessage();
}

function dbconnection() {
mysql_select_db ("vino");
}

$query = ('SELECT * FROM tablename');
$result = mysql_query($query) or die(mysql_error());
header ('Content-Type: text/csv');
header ('Content-Disposition: attachment;filename=export.csv');
$row = mysql_fetch_assoc($result);

if ($row) {
echocsv(array_keys($row));
}

while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}

function echocsv($fields) {
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>

~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*


I`m Possible

I`m Possible
"Better To Die On Your Feet Than To Live On Your Knees"