Step1: create a database called testlogin through phpmyadmin. execute the below query through phpmyadmin
1 2 3 4 5 6 7 |
CREATE TABLE IF NOT EXISTS `tbl_country` ( `id` int(10) NOT NULL AUTO_INCREMENT, `countryid` int(10) NOT NULL, `countryname` varchar(30) NOT NULL, `countrycode` varchar(30) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 |
use the below files for database connectivity and csv reading and insertion
db_connect.php
1 2 3 4 5 6 7 8 |
<?php $connection_string = mysql_connect('localhost', 'root', ''); if (!$connection_string) { die('Could not connect: ' . mysql_error()); } mysql_select_db('testlogin', $connection_string) or die('Could not select database.'); ?> |
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php include"db_connect.php"; if (($handle = fopen("country.csv", "r")) !== FALSE) { $to_avoid_firstline = true; while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { if($to_avoid_firstline) { $to_avoid_firstline = false; continue; } $num = count($data); $country_id=$data[0]; $country_name=$data[1]; $country_code=$data[2]; $query="insert into tbl_country(countryid,countryname,countrycode)values('$country_id','$country_name','$country_code')"; $result=mysql_query($query,$connection_string); } fclose($handle); } ?> |