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

Importing CSV File Data into MySQL Database using PHP Tutorial

shylock95

NFT Drop Specialist
S Rep
0
0
0
Rep
0
S Vouches
0
0
0
Vouches
0
Posts
73
Likes
17
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
In this tutorial, you will learn how to Import CSV File Data Into MySQL Database using PHP. The tutorial aims to provide the IT/CS Students and new programmers with a reference for reading CSV Files in PHP and Import Data into the Database. Here, the step-by-step tutorial with snippets is provided and a sample program source code zip that demonstrates the tutorial objectives is free to download.

How to Import Data From CSV to MySQL Database using PHP?

PHP has a built-in method that allows the server to read files such as CSV. In order to import the data from CSV to MySQL Database, you can simply read the data from the CSV File and create a MySQL Statement for inserting the data into the database.

Here are the following PHP methods that are useful for implementing an import data from CSV to Database:

  • fopen()
  • fgetcsv()
  • fclose()

Steps of implementing an import data from CSV to MySQL DB

  1. Create a form that contains a file input for choosing the CSV file.
  2. Upon submission, read the selected/chosen CSV file and list the row data.
  3. Create a MySQL Insert Statement w/ the values listed in the CSV file.
  4. Execute the MySQL Query for the Insertion of data into the database.

Example

Here are the snippets that result in a simple program that demonstrate the steps that I provided above.

Database Schema

Let us use the following MySQL Database Schema for this example web application. The schema creates a new database named dummy_db. It also creates one table named members that have id, name, phone, email, and created_at columns.

  1. --
  2. -- Database: `dummy_db`
  3. --
  4. CREATE

    DATABASE

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

    NOT

    EXISTS

    [/url] `dummy_

    db`

    DEFAULT

    CHARACTER SET

    utf8mb4 COLLATE

    utf8mb4_general_ci;
  5. USE

    `dummy_

    db`

    ;

  6. -- --------------------------------------------------------

  7. --
  8. -- Table structure for table `members`
  9. --

  10. CREATE

    TABLE

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

    NOT

    EXISTS

    [/url] `members`

    (
  11. `id`

    int

    (

    11

    )

    NOT

    NULL

    AUTO_INCREMENT

    ,
  12. `name`

    varchar

    (

    250

    )

    NOT

    NULL

    ,
  13. `phone`

    varchar

    (

    50

    )

    NOT

    NULL

    ,
  14. `email`

    varchar

    (

    100

    )

    NOT

    NULL

    ,
  15. `created_

    at`

    datetime

    NOT

    NULL

    DEFAULT

    current_timestamp

    (

    )

    ,
  16. PRIMARY KEY

    (

    `id`

    )
  17. )

    ENGINE

    =

    InnoDB

    DEFAULT

    CHARSET

    =

    utf8mb4;

Database Connection

Next, create a PHP file and save it as db-connect.php. This file contains the following script which handles the connection of the application and database.

  1. <?php
  2. // DB Host
  3. $host

    =

    "localhost"

    ;
  4. // DB Username
  5. $uname

    =

    "root"

    ;
  6. // DB Password
  7. $password

    =

    ""

    ;
  8. // DB Name
  9. $dbname

    =

    "dummy_db"

    ;


  10. $conn

    =

    new

    mysqli(

    $host

    ,

    $uname

    ,

    $password

    ,

    $dbname

    )

    ;
  11. if

    (

    !

    $conn

    )

    {
  12. die

    (

    "Database Connection Failed."

    )

    ;
  13. }
  14. ?>

Interface

Next, let's create another PHP file and save it as index.php. The file contains the following script which is a combined PHP and HTML code. As result, the page has a form that contains a file input that only accepts a CSV file. It also contains a table that displays the inserted data from the database.

  1. <?php session_start(

    )

    ; ?>
  2. <!DOCTYPE html>
  3. <html

    lang

    =

    "en"

    >
  4. <head

    >
  5. <meta

    charset

    =

    "UTF-8"

    >
  6. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  7. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  8. <title

    >

    Import CSV Data to MySQL in PHP</

    title

    >
  9. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"

    integrity=

    "sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    /

    >
  10. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"

    integrity=

    "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi"

    crossorigin=

    "anonymous"

    >

  11. <script

    src

    =

    "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js"

    integrity=

    "sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    ></

    script

    >
  12. <script

    src

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"

    integrity=

    "sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"

    crossorigin=

    "anonymous"

    ></

    script

    >
  13. </

    head

    >
  14. <body

    style

    =

    "background:#9CB4CC"

    >
  15. <nav class

    =

    "navbar navbar-expand-lg navbar-dark"

    style

    =

    "background:#06283D"

    >
  16. <div

    class

    =

    "container"

    >
  17. <a

    class

    =

    "navbar-brand"

    href

    =

    "./"

    >

    Import CSV Data to MySQL in PHP</

    a

    >
  18. <div

    >
  19. <a

    href

    =

    "https://sourcecodester.com"

    class

    =

    "text-light fw-bolder h6 text-decoration-none"

    target

    =

    "_blank"

    >

    SourceCodester</

    a

    >
  20. </

    div

    >
  21. </

    div

    >
  22. </

    nav>
  23. <div

    class

    =

    "container-fluid px-5 pb-2 pt-5"

    >
  24. <div

    class

    =

    "col-lg-6 col-md-8 col-sm-12 mx-auto"

    >
  25. <h3

    class

    =

    "text-center text-light"

    >

    Importing CSV Data to MySQL Database in PHP</

    h3

    >
  26. <hr

    >
  27. <?php if(

    isset(

    $_SESSION[

    'status'

    ]

    )

    && $_SESSION[

    'status'

    ]

    ==

    "success"

    )

    : ?>
  28. <div

    class

    =

    "alert alert-success rounded-0 mb-3"

    >
  29. <?=

    $_SESSION[

    'message'

    ]

    ?>
  30. </

    div

    >
  31. <?php unset(

    $_SESSION[

    'status'

    ]

    )

    ;unset(

    $_SESSION[

    'message'

    ]

    )

    ?>
  32. <?php endif; ?>
  33. <?php if(

    isset(

    $_SESSION[

    'status'

    ]

    )

    && $_SESSION[

    'status'

    ]

    ==

    "error"

    )

    : ?>
  34. <div

    class

    =

    "alert alert-danger rounded-0 mb-3"

    >
  35. <?=

    $_SESSION[

    'message'

    ]

    ?>
  36. </

    div

    >
  37. <?php unset(

    $_SESSION[

    'status'

    ]

    )

    ;unset(

    $_SESSION[

    'message'

    ]

    )

    ?>
  38. <?php endif; ?>
  39. <div

    class

    =

    "card rounded-0 mb-3"

    >
  40. <div

    class

    =

    "card-header rounded-0"

    >
  41. <div

    class

    =

    "card-title"

    ><b

    >

    Import Data From CSV</

    b

    ></

    div

    >
  42. </

    div

    >
  43. <div

    class

    =

    "card-body rounded-0"

    >
  44. <div

    class

    =

    "container-fluid"

    >
  45. <form

    action

    =

    "import_csv.php"

    id

    =

    "import-form"

    method

    =

    "POST"

    enctype

    =

    "multipart/form-data"

    >
  46. <div

    class

    =

    "mb-3"

    >
  47. <label

    for

    =

    "fileData"

    class

    =

    "form-label"

    >

    Browse CSV Data</

    label

    >
  48. <input

    class

    =

    "form-control"

    type

    =

    "file"

    accept

    =

    ".csv"

    name

    =

    "fileData"

    id

    =

    "fileData"

    required>
  49. </

    div

    >
  50. </

    form

    >
  51. </

    div

    >
  52. </

    div

    >
  53. <div

    class

    =

    "card-footer py-1"

    >
  54. <div

    class

    =

    "text-center"

    >
  55. <button

    class

    =

    "btn btn-primary rounded-pill col-lg-5 col-md-6 col-sm-12 col-xs-12"

    form=

    "import-form"

    >

    Import</

    button

    >
  56. </

    div

    >
  57. </

    div

    >
  58. </

    div

    >
  59. <div

    class

    =

    "card my-2 rounded-0"

    >
  60. <div

    class

    =

    "card-header rounded-0"

    >
  61. <div

    class

    =

    "card-title"

    ><b

    >

    Member List</

    b

    ></

    div

    >
  62. </

    div

    >
  63. <div

    class

    =

    "card-body rounded-0"

    >
  64. <div

    class

    =

    "container-fluid"

    >
  65. <div

    class

    =

    "table-responsive"

    >
  66. <table

    class

    =

    "table table-hovered table-striped table-bordered"

    >
  67. <thead

    >
  68. <tr

    class

    =

    "bg-gradient bg-primary text-white"

    >
  69. <th

    class

    =

    "text-center"

    >

    #</

    th

    >
  70. <th

    class

    =

    "text-center"

    >

    Name</

    th

    >
  71. <th

    class

    =

    "text-center"

    >

    Phone/Fax</

    th

    >
  72. <th

    class

    =

    "text-center"

    >

    Email</

    th

    >
  73. </

    tr

    >
  74. </

    thead

    >
  75. <tbody

    >
  76. <?php
  77. include_once(

    'db-connect.php'

    )

    ;
  78. $members_sql =

    "SELECT * FROM `members` order by id ASC"

    ;
  79. $members_qry =

    $conn->

    query($members_sql);
  80. if($members_qry->num_rows > 0):
  81. while($row = $members_qry->fetch_assoc()):
  82. ?>
  83. <tr

    >
  84. <th

    class

    =

    "text-center"

    ><?=

    $row[

    'id'

    ]

    ?></

    th

    >
  85. <td

    ><?=

    $row[

    'name'

    ]

    ?></

    td

    >
  86. <td

    ><?=

    $row[

    'phone'

    ]

    ?></

    td

    >
  87. <td

    ><?=

    $row[

    'email'

    ]

    ?></

    td

    >
  88. </

    tr

    >
  89. <?php endwhile; ?>
  90. <?php else: ?>
  91. <tr

    >
  92. <th

    class

    =

    "text-center"

    colspan

    =

    "4"

    >

    No data on the database yet.</

    th

    >
  93. </

    tr

    >
  94. <?php endif; ?>
  95. <?php $conn->

    close() ?>
  96. </

    tbody

    >
  97. </

    table

    >
  98. </

    div

    >
  99. </

    div

    >
  100. </

    div

    >
  101. </

    div

    >
  102. </

    div

    >

  103. </

    div

    >
  104. </

    body

    >
  105. </

    html

    >

PHP API

Next, we will create the PHP API that contains the scripts for reading the selected CSV File, listing the data to insert, and inserting the data into the database. Save the following snippet as import_csv.php. This file will be executed upon form submission.

  1. <?php
  2. session_start

    (

    )

    ;
  3. include_once

    (

    'db-connect.php'

    )

    ;

  4. /**
  5. * Check if CSV File has been sent successfully otherwise return error
  6. */
  7. if

    (

    isset

    (

    $_FILES

    [

    'fileData'

    ]

    )

    &&

    !

    empty

    (

    $_FILES

    [

    'fileData'

    ]

    [

    'tmp_name'

    ]

    )

    )

    {

  8. // Read CSV File
  9. $csv_file

    =

    fopen

    (

    $_FILES

    [

    'fileData'

    ]

    [

    'tmp_name'

    ]

    ,

    "r"

    )

    ;

  10. // Row Iteration
  11. $rowCount

    =

    0

    ;

  12. //Data to insert for batch insertion
  13. $data

    =

    [

    ]

    ;

  14. // Read CSV Data by row
  15. while

    (

    (

    $row

    =

    fgetcsv

    (

    $csv_file

    ,

    1000

    ,

    ","

    )

    )

    !==

    FALSE

    )

    {
  16. if

    (

    $rowCount

    >

    0

    )

    {
  17. //Sanitizing Data
  18. $name

    =

    addslashes

    (

    $conn

    ->

    real_escape_string

    (

    $row

    [

    0

    ]

    )

    )

    ;
  19. $phone

    =

    addslashes

    (

    $conn

    ->

    real_escape_string

    (

    $row

    [

    1

    ]

    )

    )

    ;
  20. $email

    =

    addslashes

    (

    $conn

    ->

    real_escape_string

    (

    $row

    [

    2

    ]

    )

    )

    ;

  21. // Add Row data to insert value
  22. $data

    [

    ]

    =

    "('{$name}

    ', '{$phone}

    ', '{$email}

    ')"

    ;
  23. }
  24. $rowCount

    ++;
  25. }

  26. // Close the CSV File
  27. fclose

    (

    $csv_file

    )

    ;

  28. /**
  29. * Check if there's a data to insert otherwise return error
  30. */
  31. if

    (

    count

    (

    $data

    )

    >

    0

    )

    {
  32. // Convert Data values from array to string w/ comma seperator
  33. $insert_values

    =

    implode

    (

    ", "

    ,

    $data

    )

    ;

  34. //MySQL INSERT Statement
  35. $insert_sql

    =

    "INSERT INTO `members` (`name`, `phone`, `email`) VALUES {$insert_values}

    "

    ;

  36. // Execute Insertion
  37. $insert

    =

    $conn

    ->

    query

    (

    $insert_sql

    )

    ;

  38. if

    (

    $insert

    )

    {
  39. // Data Insertion is successful
  40. $_SESSION

    [

    'status'

    ]

    =

    'success'

    ;
  41. $_SESSION

    [

    'message'

    ]

    =

    'Data has been imported succesfully.'

    ;
  42. }

    else

    {
  43. // Data Insertion has failed
  44. $_SESSION

    [

    'status'

    ]

    =

    'error'

    ;
  45. $_SESSION

    [

    'message'

    ]

    =

    'Import Failed! Error: '

    .

    $conn

    ->

    error

    ;
  46. }
  47. }

    else

    {
  48. $_SESSION

    [

    'status'

    ]

    =

    'error'

    ;
  49. $_SESSION

    [

    'message'

    ]

    =

    'CSV File Data is empty.'

    ;
  50. }

  51. }

    else

    {
  52. $_SESSION

    [

    'status'

    ]

    =

    'error'

    ;
  53. $_SESSION

    [

    'message'

    ]

    =

    'CSV File Data is missing.'

    ;
  54. }
  55. $conn

    ->

    close

    (

    )

    ;

  56. header

    (

    'location: ./'

    )

    ;
  57. exit

    ;
  58. ?>

CSV File

Lastly, let's create a CSV file that we will use for importing. You can create your own example CSV file but make sure to follow the following format of data with the same column order. Take note that the script for importing the source code skips the first row in the reading. The CSV file only requires the name, phone, and email columns.

name,phone,email
Silas Leonard,(515) 433-7885,[email protected]
Adele Moody,1-451-357-4702,[email protected]
Colton Turner,1-172-865-3080,[email protected]
Carolyn Kramer,1-237-334-8685,[email protected]
Lionel Vazquez,1-226-236-8055,[email protected]
Naomi Workman,(320) 551-7707,[email protected]
Rhona Vega,1-683-547-2283,[email protected]
Martena Hardin,1-426-208-8881,[email protected]
Galena Collier,1-711-578-8491,[email protected]
Demetrius Nichols,1-302-469-9766,[email protected]

There you go! You can now test the application on your end and see if it works as we planned. I also provided the source code zip file that I created for this tutorial with a sample CSV File. You can download it by clicking the Download Button located below this article's content.

Snapshot

Here is a snapshot of the application page interface.

That's it! That's the end of this tutorial. I hope this Importing CSV File Data into MySQL Database using PHP Tutorial helps you with what you are looking for and that you'll find this useful for your current and future PHP Projects.

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

Happy Coding:)


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

452,496

331,765

331,773

Top