Reading CSV File in PHP | PHP Tutorial For Beginners

This tutorial shows you how to read a CSV file using PHP and store the data into a database. CSV is a file format that stores comma-separated values. We read the CSV file line by line and insert each row into the database.

We must be aware of importing data into a database. Data used for importing is normally in the form of a text file. Sometimes these files are called comma-separated value files, which will normally have a .csv extension.

Step 1 — Create the CSV File

Create a CSV file with your data. In this example the CSV file contains the following columns:

Name,Address,Phone
ABC,XYZ,12345

Step 2 — Create upload.php

Create a PHP file named upload.php and paste the following code into it:

<?php
/*--- Database connection ---*/
$hostname_conn = "localhost";
$database_conn = "upload";
$username_conn = "root";
$password_conn = "";

$conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn);
mysql_select_db($database_conn, $conn) or die("could not select db");

if (isset($_FILES['userfile']['name'])) {
    $ext = strrchr($_FILES['userfile']['name'], ".");

    if ($ext == ".csv") {

        // Store file in temporary folder.
        move_uploaded_file($_FILES['userfile']['tmp_name'],
            "files/" . $_FILES['userfile']['name']);

        // Read content of the file.
        $file = file("files/" . $_FILES['userfile']['name']);

        foreach ($file as $key => $line) {

            // Reading from the second line (skip header row).
            if ($key >= 1) {
                $var = explode(",", $line);

                // Store content into database.
                $query = "INSERT INTO mytable VALUES('"
                    . $var[0] . "','" . $var[1] . "'," . $var[2] . ")";
                mysql_query($query) or die();
            }
        }

    } else {
        $error = "File must be in CSV format. You uploaded a "
               . $ext . " file.";
    }
}
?>

<html>
<head>
  <title>Upload CSV File</title>
</head>
<body>
  <h3>Upload CSV File</h3>
  <?php if (!empty($error)) echo "<p style='color:red'>$error</p>"; ?>
  <form action="" method="post" enctype="multipart/form-data">
    <p>
      <input type="file" name="userfile" id="userfile" size="45">
    </p>
    <p>
      <input type="submit" name="Submit" value="Upload">
    </p>
  </form>
</body>
</html>

How It Works

  • The form submits the file via enctype="multipart/form-data".
  • PHP checks the extension — only .csv files are accepted.
  • The uploaded file is moved to a files/ directory.
  • file() reads the CSV into an array, one line per element.
  • The loop skips the header row ($key >= 1) and uses explode(",",$line) to split each row by comma before inserting into the database.

Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.

← Older Post Newer Post →