<?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();
?>
~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$