Here is the simple way to upload/import csv file Database.
You can find below the procedure to upload/import csv file:
1.Make a database in mysql.
2.Make a table in your database like
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `contacts`;
CREATE TABLE `contacts` (
`contact_id` int(11) NOT NULL auto_increment,
`contact_first` varchar(255) character set latin1 default NULL,
`contact_last` varchar(255) character set latin1 default NULL,
`contact_designation` varchar(255) character set latin1 default NULL,
`contact_email` varchar(255) character set latin1 default NULL,
`contact_last` varchar(255) character set latin1 default NULL,
PRIMARY KEY (`contact_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
3. Now make a page Index.php to select csv file.
<?php
$connect = mysql_connect("localhost","root","root");
mysql_select_db("practise",$connect);
if ($_FILES[csv][size] > 0) {
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
do {
if ($data[0]) {
mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."',
'".addslashes($data[4])."',
'".addslashes($data[5])."',
'".addslashes($data[6])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
header('Location: csv.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
No comments:
Post a Comment