• We just launched and are currently in beta. Join us as we build and grow the community.

How to Import CSV Data in PHP CodeIgniter Framework

kldzn

Social Post Curator
K Rep
0
0
0
Rep
0
K Vouches
0
0
0
Vouches
0
Posts
105
Likes
192
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 500 XP
Importing CSV data into applications is a common practice. However, CodeIgniter Framework does not out of the box have this functionality as it does not have a library that does this. We will be using a csvimport.php library written by Bradstinson. This can be downloaded at github. This library converts CSV data to an array which can be looped through and saved into a database table.

Getting Started

First, you must download and install any local web server such as XAMPP/WAMP. After that, open the XAMPP/WAMP's Control Panel and start the "Apache" and "MySQL".

Download the latest version of CodeIgniter 3.1.11.Extract the zipped folder and copy the application folder, system folder, and index.php to the folder you will create in your site root called ciaddressimport. Go to "application/config" folder and edit the Base URL to "http://localhost/ciaddressimport/". Go to your browser and browse "http://localhost/ciaddressimport". You will now see the Codeigniter welcome page. This shows Codeigniter was successfully installed.

Download also Bootstrap for the design. Create new folder inside your "ciaddressimport" naming "assets". Extract the bootstrap and copy the folders then paste it into the "assetes" folder.

Copy the csvimport.php library downloaded from Github into "Applications/Libraries" folder. The library will be loaded in our controller.

Creation of Database

Open PHPMyAdmin and create a database called “ciaddressimport”. Also create a table with the following query.

  1. CREATE

    TABLE

    [url=http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html]IF

    NOT

    EXISTS

    [/url] `addressbook`

    (
  2. `id`

    int

    (

    11

    )

    NOT

    NULL

    AUTO_INCREMENT

    ,
  3. `firstname`

    varchar

    (

    255

    )

    DEFAULT

    NULL

    ,
  4. `lastname`

    varchar

    (

    255

    )

    DEFAULT

    NULL

    ,
  5. `phone`

    varchar

    (

    100

    )

    DEFAULT

    NULL

    ,
  6. `email`

    varchar

    (

    255

    )

    DEFAULT

    NULL

    ,
  7. PRIMARY KEY

    (

    `id`

    )
  8. )

    ENGINE

    =

    InnoDB

    ;

You can generate some dummy data for the table at

www.generatedata.com
Database Connection

Open database.php in the config (application/config) folder and set your database parameters as follows.

  1. $db

    [

    'default'

    ]

    [

    'hostname'

    ]

    =

    'localhost'

    ;
  2. $db

    [

    'default'

    ]

    [

    'username'

    ]

    =

    'root'

    ;
  3. $db

    [

    'default'

    ]

    [

    'password'

    ]

    =

    ''

    ;
  4. $db

    [

    'default'

    ]

    [

    'database'

    ]

    =

    'ciaddressimport'

    ;

Note: This configuration is for Wamp, if you are using Mamp , Xampp or Lamp set yours as required.

Route Configuration

Open the routes.php in "Application/Config folder". Change the default controller from "welcom" to "csv".

  1. $route

    [

    'default_controller'

    ]

    =

    "csv"

    ;

Autoload Configuration

Open the autoload.php in the "application/config". Then configure to load automatically the "db" library for the database connection and "URL" helper for the base URL usage. Follow the code below.

  1. $autoload

    [

    'libraries'

    ]

    =

    array

    (

    'database'

    )

    ;

  1. $autoload

    [

    'helper'

    ]

    =

    array

    (

    'url'

    )

    ;

Creation of CSV Model

Create a new model file in the model folder called "csv_model.php" inside "application/models". Add the following code:

  1. <?php

  2. class

    Csv_model extends

    CI_Model {

  3. function

    __construct(

    )

    {
  4. parent::

    __construct(

    )

    ;

  5. }

  6. function

    get_addressbook(

    )

    {
  7. $query

    =

    $this

    ->

    db

    ->

    get

    (

    'addressbook'

    )

    ;
  8. if

    (

    $query

    ->

    num_rows

    (

    )

    >

    0

    )

    {
  9. return

    $query

    ->

    result_array

    (

    )

    ;
  10. }

    else

    {
  11. return

    FALSE

    ;
  12. }
  13. }

  14. function

    insert_csv(

    $data

    )

    {
  15. $this

    ->

    db

    ->

    insert

    (

    'addressbook'

    ,

    $data

    )

    ;
  16. }
  17. }
  18. /*END OF FILE*/

Creation of Controller

Create a New controller called csv.php in the controllers folder and add the following code:

  1. <?php

  2. class

    Csv extends

    CI_Controller {

  3. function

    __construct(

    )

    {
  4. parent::

    __construct(

    )

    ;
  5. $this

    ->

    load

    ->

    model

    (

    'csv_model'

    )

    ;
  6. $this

    ->

    load

    ->

    library

    (

    'csvimport'

    )

    ;
  7. }

  8. function

    index(

    )

    {
  9. $data

    [

    'addressbook'

    ]

    =

    $this

    ->

    csv_model

    ->

    get_addressbook

    (

    )

    ;
  10. $this

    ->

    load

    ->

    view

    (

    'csvindex'

    ,

    $data

    )

    ;
  11. }

  12. function

    importcsv(

    )

    {
  13. $data

    [

    'addressbook'

    ]

    =

    $this

    ->

    csv_model

    ->

    get_addressbook

    (

    )

    ;
  14. $data

    [

    'error'

    ]

    =

    ''

    ;

    //initialize image upload error array to empty

  15. $config

    [

    'upload_path'

    ]

    =

    './uploads/'

    ;
  16. $config

    [

    'allowed_types'

    ]

    =

    'csv'

    ;
  17. $config

    [

    'max_size'

    ]

    =

    '1000'

    ;

  18. $this

    ->

    load

    ->

    library

    (

    'upload'

    ,

    $config

    )

    ;


  19. // If upload failed, display error
  20. if

    (

    !

    $this

    ->

    upload

    ->

    do_upload

    (

    )

    )

    {
  21. $data

    [

    'error'

    ]

    =

    $this

    ->

    upload

    ->

    display_errors

    (

    )

    ;

  22. $this

    ->

    load

    ->

    view

    (

    'csvindex'

    ,

    $data

    )

    ;
  23. }

    else

    {
  24. $file_data

    =

    $this

    ->

    upload

    ->

    data

    (

    )

    ;
  25. $file_path

    =

    './uploads/'

    .

    $file_data

    [

    'file_name'

    ]

    ;

  26. if

    (

    $this

    ->

    csvimport

    ->

    get_array

    (

    $file_path

    )

    )

    {
  27. $csv_array

    =

    $this

    ->

    csvimport

    ->

    get_array

    (

    $file_path

    )

    ;
  28. foreach

    (

    $csv_array

    as

    $row

    )

    {
  29. $insert_data

    =

    array

    (
  30. 'firstname'

    =>

    $row

    [

    'firstname'

    ]

    ,
  31. 'lastname'

    =>

    $row

    [

    'lastname'

    ]

    ,
  32. 'phone'

    =>

    $row

    [

    'phone'

    ]

    ,
  33. 'email'

    =>

    $row

    [

    'email'

    ]

    ,
  34. )

    ;
  35. $this

    ->

    csv_model

    ->

    insert_csv

    (

    $insert_data

    )

    ;
  36. }
  37. $this

    ->

    session

    ->

    set_flashdata

    (

    'success'

    ,

    'Csv Data Imported Succesfully'

    )

    ;
  38. redirect(

    base_url(

    )

    .

    'csv'

    )

    ;
  39. //echo "<pre>"; print_r($insert_data);
  40. }

    else
  41. $data

    [

    'error'

    ]

    =

    "Error occured"

    ;
  42. $this

    ->

    load

    ->

    view

    (

    'csvindex'

    ,

    $data

    )

    ;
  43. }

  44. }

  45. }
  46. /*END OF FILE*/

Creation of the Interface

Go to your views (application/views) folder and create file called csvindex.php Add the following code:

  1. <!DOCTYPE HTML>
  2. <html

    >
  3. <head

    >
  4. <meta

    charset

    =

    "utf-8"

    >
  5. <title

    >

    Adddress Book Project</

    title

    >
  6. <link

    href

    =

    "<?php echo base_url(); ?>

    assets/bootstrap/css/bootstrap.css" type="text/css" rel="stylesheet" />
  7. <link

    href

    =

    "<?php echo base_url(); ?>

    assets/css/styles.css" type="text/css" rel="stylesheet" />

  8. <script

    src

    =

    "<?php echo base_url(); ?>

    assets/js/jquery.js" type="text/javascript"></

    script

    >
  9. <script

    src

    =

    "<?php echo base_url(); ?>

    assets/bootstrap/js/bootstrap.min.js"></

    script

    >
  10. </

    head

    >

  11. <body

    >

  12. <div

    class

    =

    "navbar navbar-inverse navbar-fixed-top"

    >
  13. <div

    class

    =

    "navbar-inner"

    >
  14. <div

    class

    =

    "container"

    >
  15. <a

    class

    =

    "btn btn-navbar"

    data-toggle=

    "collapse"

    data-target

    =

    ".nav-collapse"

    >
  16. <span

    class

    =

    "icon-bar"

    ></

    span

    >
  17. <span

    class

    =

    "icon-bar"

    ></

    span

    >
  18. <span

    class

    =

    "icon-bar"

    ></

    span

    >
  19. </

    a

    >
  20. <a

    class

    =

    "brand"

    href

    =

    "#"

    >

    My Address book</

    a

    >
  21. <div

    class

    =

    "nav-collapse collapse"

    >
  22. <ul

    class

    =

    "nav"

    >
  23. <li

    class

    =

    "active"

    ><a

    href

    =

    "<?php echo base_url(); ?>

    "><i

    class

    =

    "icon-home"

    ></

    i

    >

    Home</

    a

    ></

    li

    >
  24. <li

    ><a

    href

    =

    "#about"

    >

    About</

    a

    ></

    li

    >
  25. </

    ul

    >
  26. </

    div

    >

    <!--/.nav-collapse -->
  27. </

    div

    >
  28. </

    div

    >
  29. </

    div

    >

  30. <div

    class

    =

    "container"

    style

    =

    "margin-top:50px"

    >
  31. <br

    >

  32. <?php if (

    isset(

    $error)

    )

    : ?>
  33. <div

    class

    =

    "alert alert-error"

    ><?php echo $error; ?></

    div

    >
  34. <?php endif; ?>
  35. <?php if (

    $this->

    session->flashdata('success') == TRUE): ?>
  36. <div

    class

    =

    "alert alert-success"

    ><?php echo $this->

    session->flashdata('success'); ?></

    div

    >
  37. <?php endif; ?>

  38. <h2

    >

    CI Addressbook Import</

    h2

    >
  39. <form

    method

    =

    "post"

    action

    =

    "<?php echo base_url() ?>

    csv/importcsv" enctype="multipart/form-data">
  40. <input

    type

    =

    "file"

    name

    =

    "userfile"

    ><br

    ><br

    >
  41. <input

    type

    =

    "submit"

    name

    =

    "submit"

    value

    =

    "UPLOAD"

    class

    =

    "btn btn-primary"

    >
  42. </

    form

    >

  43. <br

    ><br

    >
  44. <table

    class

    =

    "table table-striped table-hover table-bordered"

    >
  45. <caption

    >

    Address Book List</

    caption

    >
  46. <thead

    >
  47. <tr

    >
  48. <th

    >

    First Name</

    th

    >
  49. <th

    >

    Last Name</

    th

    >
  50. <th

    >

    Phone</

    th

    >
  51. <th

    >

    Email</

    th

    >
  52. </

    tr

    >
  53. </

    thead

    >
  54. <tbody

    >
  55. <?php if (

    $addressbook ==

    FALSE)

    : ?>
  56. <tr

    ><td

    colspan

    =

    "4"

    >

    There are currently No Addresses</

    td

    ></

    tr

    >
  57. <?php else: ?>
  58. <?php foreach (

    $addressbook as $row)

    : ?>
  59. <tr

    >
  60. <td

    ><?php echo $row[

    'firstname'

    ]

    ; ?></

    td

    >
  61. <td

    ><?php echo $row[

    'lastname'

    ]

    ; ?></

    td

    >
  62. <td

    ><?php echo $row[

    'phone'

    ]

    ; ?></

    td

    >
  63. <td

    ><?php echo $row[

    'email'

    ]

    ; ?></

    td

    >
  64. </

    tr

    >
  65. <?php endforeach; ?>
  66. <?php endif; ?>
  67. </

    tbody

    >
  68. </

    table

    >


  69. <hr

    >
  70. <footer>
  71. <p

    >

    &copy;

    My Address Book</

    p

    >
  72. </

    footer>

  73. </

    div

    >



  74. </

    body

    >
  75. </

    html

    >

Demo

Explanations

In the model file ci_model.php, on lines 10-17, we queried our address book table to get all address book records. The data retrieved will be displayed in the csvindex.php view. Lines 19-21 contains the query that inserts each row of records into the table.

In the controller file csv.php, on lines 7-8, we loaded the csvimport.php library and csv_model.php model in the CSV class constructor. On lines 11-14, we created a default index method that fetches the address from the database and sends it to the csvindex.php view. On lines 16-53, The "csvimport" method handles the CSV import functionality. First, we initialize the upload error to an empty string, Next, we set some configuration parameters for the file that is uploaded which included the upload location, the allowed file type which is CSV, and the maximum size of an uploaded file. Then we try to upload the file and if it fails we set the error message and call the csvindex.php view to show the error. However, if the upload was successful, we get the file path of the file uploaded, we then call the get_array method of the csvimport library and assign it to a variable called $csv_array. But if the get_array method failed, we show appropriate error in the csvindex.php view. We then loop through the $csv_array variable using the foreach loop. While looping through the $csv_array data, we insert the records one at a time into the addressbook table by calling the insert_csv method of the csv_model class. Once the loop is complete, we then set a session message called "success" and redirect the user to the home page. This success message is then displayed in the home page and the new records inserted are displayed in the table.

Note: The csvimport.php library assumes the first row of your csv file is the column name

In the csvindex.php view, on lines 37 to 39 we check if there is an error message, then we display the error. We also check if there is a session message called "success", then we display the success message. Lines 45-48 displays the upload form. As you can see we set the enctype="multipart/form-data" because it contains file upload. On lines 62-73, we loop through the "addressbook" data and display all the records.

That's the end of this tutorial. I hope this tutorial will help you with what you are looking for.

Enjoy Coding :)

Explore more on this website for more Tutorials and Free Project Source Codes.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.

2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,496

327,690

327,698

Top