Uploading and storing CSV into mysql db using PHP

291 views Asked by At

I'm trying to create a file upload form in which te user can simply upload a CSV and then it's parsed and values are uploaded in a mysql database. I have already managed to get a lot of my code working. Here's what I have so far:

HTML of upload form:

<form method="post"
        enctype="multipart/form-data">
<table>
    <tr>
        <td>
            Filename:
        </td>
        <td>
            <input type="file" name="file" id="file">
        </td>
    </tr>
    <tr>
        <td colspan="2" align="right">
            <input type="submit" name="submit" value="Submit">
        </td>
    </tr>
</table>
</form>

PHP code I have so far:

<?php
if(isset($_POST['submit'])) {
    if ($_FILES["file"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file"]["error"] . "<br>";
    }
    else
    {
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";
        $a=$_FILES["file"]["tmp_name"];
    }   

    $csv_file = $a; 

    if (($getfile = fopen($csv_file, "r")) !== FALSE) {
       while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {

                $result = $data;
                $str = implode(";", $result);
                $slice = explode(";", $str);

                $col1 = $slice[0];
                $col2 = $slice[1];
                $col3 = $slice[2];
                $col4 = $slice[3];

                $query = "INSERT INTO persons(id, name, email ,contacts) VALUES('".$col1."','".$col2."','".$col3."','".$col4."')";
                mysql_query($query);
                echo $query;

        }
    }
    echo "File data successfully imported to database!!";
}
?>

Now the problem is when I'm reading the file and try to create an array of it I don't get a multidimensional array so that I can query row by row. When I look into the $slice array it looks like this:

Array
(
    [0] => 1
    [1] => Jack
    [2] => [email protected]
    [3] => Bart
2
    [4] => Bart
    [5] => [email protected]
    [6] => John
3
    [7] => John
    [8] => [email protected]
    [9] => Jack
)

When I echo out the query that I get with this script I get:

INSERT INTO persons(id, name, email ,contacts) VALUES('1','Jack','[email protected]','Bart 2')

How can I fix this so I get a db row for every row in my csv? I hope I gave enough information to solve my question.

1

There are 1 answers

0
Shri On

Try this,

if (($getfile = fopen($csv_file, "r")) !== FALSE) {
     while($data = ! feof($getfile ))   {           

            $query = "INSERT INTO persons(id, name, email ,contacts) VALUES('".fgetcsv($getfile[0] )."','".fgetcsv($getfile[1])."','".fgetcsv($getfile[2] )."','".fgetcsv($getfile[3] )."')";
            mysql_query($query);
            echo $query;

    }
}