How to import excel and CSV file in CodeIgniter framework MySQL
In this example we are going to show you how to How to import excel and CSV file in CodeIgniter framework MySQL PHP.
Here we using 3 files for import data in CodeIgniter framework MySQL PHP:
- Crud.php Path: codeIgniter\application\controllers\Crud.php
- Crud_model.php Path: codeIgniter\application\models\Crud_model.php
- import_data.php Path: codeIgniter\application\views\import_data.php
Crud.php (Controller)
<?php
class Crud extends CI_Controller
{
public function __construct()
{
parent::__construct();/* call CodeIgniter's default Constructor */
$this->load->database();/* load database libray manually */
$this->load->model('Crud_model');/* load Model */
}
public function importdata()
{
$this->load->view('import_data');
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;//
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$fname = $filesop[0];
$lname = $filesop[1];
if($c<>0){ /* SKIP THE FIRST ROW */
$this->Crud_model->saverecords($fname,$lname);
}
$c = $c + 1;
}
echo "sucessfully import data !";
}
}
}
?>
Crud_model.php (Model)
<?php
class Crud_model extends CI_Model
{
function saverecords($fname,$lname)
{
$query="insert into user values('$fname','$lname')";
$this->db->query($query);
}
}
insert.php (View)
<!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="submit" value="submit">Upload</button>
</form>
</body>
</html>
Run the program on your browser with URL:
http://localhost/codeIgniter/index.php/Crud/importdata
Comments
Post a Comment