Create Table In Your Database:
CREATE TABLE IF NOT EXISTS `csvtbl`( `ID` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `city` varchar(50) NOT NULL, PRIMARY KEY (`ID`) );import.php File
<?php
//database connection details
$connect = mysql_connect('localhost','root','password')or die('Could not connect to MySQL: ' . mysql_error());
//your database name
$cid =mysql_select_db('databasename',$connect);
// path where your CSV file is located
define('CSV_PATH','C:/wamp/www/');
// Name of your CSV file
$csv_file = CSV_PATH . "yourfilename.csv";
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 csvtbl(ID,name,city) VALUES('".$col1."','".$col2."','".$col3."')";
$s=mysql_query($query, $connect );
}
}
}
echo "Data successfully imported to database!!";
mysql_close($connect);
?>





No comments:
Post a Comment