# Upload Data From Excel File To Database.
#<?php Starts
$error_data = "";
$success_data = "";
if(isset($_POST["Import"]))
{
//First we need to make a connection with the database
$host = 'localhost'; // Host Name.
$db_user = 'root'; //User Name
$db_password= '';
$db = 'demo'; // Database Name.
$table = "excel_upload";
$conn = mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
if(!empty($_FILES)){
$posted_file = $_FILES;
//echo "<pre>";print_r($_FILES);print_r($file_ext);echo "</pre>";
$filename = $_FILES["file"]["tmp_name"];
//filename
$posted_filename = $_FILES["file"]["name"];
//file extension
$file_ext = pathinfo($posted_filename, PATHINFO_EXTENSION);
$allowed_files = array('csv','CSV');
//check uploaded file formats
if(in_array( $file_ext, $allowed_files) ) {
if($_FILES["file"]["size"] > 0)
{
//=============================
$file = fopen($filename, "r");
$count = 0; // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$count++;
//It removes the Header Data (1st Row)
if($count>1 ){
//record in table
//$sql = "INSERT into excel_upload(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
$sql = "INSERT INTO excel_upload SET
p_bench = '$emapData[0]',
p_name = '$emapData[1]',
p_price = '$emapData[2]',
p_reason= '$emapData[3]'
";
$recorded_result = mysql_query($sql);
if($recorded_result){
$success_data = "Uploaded Successfully";
//header("Location:excel_upload.php");
//die;
}else{
$error_data = "FAILED TO UPLOAD";
}
}
}
//================================
}
}else{
$error_data = 'Invalid File: Please Upload CSV File';
}
}else{
$error_data = 'File Not Found';
}
}
#?>phpEnds
## The HTML Page::
<!DOCTYPE html>
<html>
<head>
<title>Excel Upload</title>
</head>
<body>
<div style="margin:20px;">
<?php
if(!empty($error_data)){
echo "<span style='color:red;'>".$error_data."</span>";
}else if(!empty($success_data)){
echo "<span style='color:green;'>".$success_data."</span>";
}
?>
</div>
<section style="margin:20px;">
<form enctype="multipart/form-data" method="post" role="form">
<div class="form-group">
<label for="exampleInputFile">File Upload</label>
<input type="file" name="file" id="file" size="150">
<p class="help-block">Only Excel/CSV File Import.</p>
</div>
<button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button>
</form>
</section>
</body>
</html>
Sample: Excel File Data Pattern
