Importing excel file to MySQL database using PHP



[code]<form class="com-mail" method="post" action="#" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="form-group">
<input type="file" class="form-control" name="file" required>
</div>
</div>

</div>

</div>
<div class="modal-footer">
<button class="btn btn-danger" type="button" data-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
<button class="btn btn-success" id="mySubmit" name="import" type="submit"><i class="fa fa-save"></i> Upload</button>
</div>
</form>[/code]


[code]$conn = mysqli_connect("server","username","password","database");
require_once('vendorb/php-excel-reader/excel_reader2.php');
require_once('vendorb/SpreadsheetReader.php');
$gd=date("d-m-Y-h-i-s-A");

if (isset($_POST["import"]))
{


$targetPath = 'uploads/'.$gd.'_'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);

$Reader = new SpreadsheetReader($targetPath);

$sheetCount = count($Reader->sheets());

for($i=0;$i<$sheetCount;$i++)
{
$Reader->ChangeSheet($i);

foreach ($Reader as $Row)
{

$fname = "";
if(isset($Row[0])) {
$fname = mysqli_real_escape_string($conn,$Row[0]);
}

$lname = "";
if(isset($Row[1])) {
$lname= mysqli_real_escape_string($conn,$Row[1]);
}
$phone = "";
if(isset($Row[2])) {
$phone = mysqli_real_escape_string($conn,$Row[2]);
}

$phonebook = "";
if(isset($Row[3])) {
$phonebook= mysqli_real_escape_string($conn,$Row[3]);
}


if (!empty($phone)) {
$query = "insert ignore into contacts(fname,lname,phone,phonebook)
values('".$fname."','".$lname."','".$phone."','".$phonebook."')";
$result = mysqli_query($conn, $query);

if (! empty($result)) {
header("location: contacts.php?status=success&pb=all");
} else {
header("location: contacts.php?status=error&pb=all");

}
}
}

}
}

[/code]

Download

Leave a Reply

Your email address will not be published. Required fields are marked *