Import data from CSV file to mysql database using PHP
<?php
$host = "localhost"
$user = username;
$password = database password;
$db =database name;
$con = new mysqli($host,$user,$password, $db);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
?>
<html>
<head>
<style type='text/css'>
body
{
margin: 0;
padding: 0;
background-color:#FFFFFF;
text-align:center;
}
.top-bar
{
width: 100%;
height: auto;
text-align: center;
background-color:#FFF;
border-bottom: 1px solid #000;
margin-bottom: 20px;
}
.inside-top-bar
{
margin-top: 5px;
margin-bottom: 5px;
}
.link
{
font-size: 18px;
text-decoration: none;
background-color: #000;
color: #FFF;
padding: 5px;
}
.link:hover
{
background-color: #FCF3F3;
}
</style>
</head>
<body>
<div class='top-bar'>
<div class='inside-top-bar'>Import CSV file to mysql table <br><br>
</div>
</div>
<div style='text-align:left; border:1px solid #333333; width:300px; margin:0 auto; padding:10px;'>
<form name='import' method='post' enctype='multipart/form-data'>
<input type='file' name='file' /><br />
<input type='submit' name='submit' value='Submit' />
</form>
<?php
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$fetch = $con->query("SELECT username FROM tablename"); //tablename in which you import the data
$i=0;
while($fetch_array = mysqli_fetch_array($fetch)){ //checks if the record already exist or not. if exist it skips
$variablename[$i++]=$fetch_array["columnname"]; // columnname in column which is unique
}
$handle = fopen($file, 'r');
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ',')) !== false)
{
if($filesop[0]=="columnname in csv" || $filesop[0]=="" || in_array(fieldname,array of table))
continue;
///////////////////////////////////// just for reference
$name = $filesop[1];
$username = $filesop[3];
$email = $filesop[2];
$password = $filesop[4];
$password = md5($password);
$created_on = $filesop[0];
/////////////////////////////////////// values as above variables
$sql = $con->query("INSERT INTO table name (columnnames) VALUES ('"values");
$c = $c + 1;
}
if($c){
echo "You database has imported successfully. You have inserted ". $c ." records";
}else{
echo "no record inserted.";
}
}
?>
</div>
</body>
</html>
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment