PHP MVC CodeIgniter Laravel Core PHP MORE

How to import excel and CSV file using PHP MVC, MySQL


In this example we using Models, Views, Controller Structure for import excel and CSV file in PHP MVC.

To import excel and CSV file first we have to create a Controller file.

controller/hello.php

<?php
class Hello extends Controller {
	function __construct() {
		parent::__construct();
		/* Session::init(); */
	}
	function import(){
			if(isset($_POST['save']))
			{
					$file = $_FILES['file']['tmp_name'];
					$handle = fopen($file, "r");
					$c = 0;/*
					while(($filesop = fgetcsv($handle, 1000, ",")) !== false)*/
					{
						$name = $filesop[0];
						$email = $filesop[1];
						$contact = $filesop[2];
						$data = array(
							'id'=> null,
							'name' =>$name,
							'email' =>$email,
							'contact' => $contact
						);
						if($c<>0){					/*SKIP THE FIRST ROW*/
							$this->model->submit_index($data);
						}
						$c = $c + 1;
					}
					echo "Data imported successfully !"	;
			}
			$this->view->render('hello/import_data');
	}
	
}

Here is the model file which we are using for inserting data to database.

The file index_model.php is created under Models folder

models/hello_Model.php

index_model.php

<?php
class Hello_Model extends Model
{
	public function __construct()
	{
		parent::__construct();
	}
	public function submit_index($data)
	{
		$this->db->insert('user_data', $data);
	}
}	

Here is the view file index.php which inside views folder contains the form.

views/hello/index.php

<!DOCTYPE html>
<html>
<body>
<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="save" value="submit">Upload</button>
</form>
</body>
</html>

views/hello/import_data.php

<form action="<?php echo URL; ?>hello/verification" method="post" onsubmit="return confirm('Do you really want to submit the form?');">
	<center><input class="" name="otp" id="name" placeholder="Enter OTP"><br><br>
	<button type="submit" class="btn-info" value="submit" name="save">Submit</button>
	<button type="submit" class="btn-info" value="submit" name="resend">Resend</button></center>
</form>
Path: localhost/project_folder_name/view_folder_name/view_filename
Example: localhost/mvc/hello/import