tags:

views:

477

answers:

2

Hi,

I want the following functionality using php

I have a csv file. Each file corresponds to a row in my database

There is a html form that will allow me to choose the csv file.

Then once the form is submitted, I must parse the csv file and insert data into the db accordingly

How do I go about doing this ?

A: 

Here you go Anand:

http://www.chipmunk-scripts.com/board/index.php?forumID=43&ID=9602

Importing CSV files into a MySQL database, using PHP.

Neurofluxation
Bad example. It only works when both server and client runs at physically same machine.
BalusC
+4  A: 

Reading a CSV file can generally be done using the fgetcsv function (depending on your kind of CSV file, you might have to specify the delimiter, separator, ... as parameters)


Which means that going through you file line by line would not be much garder than something like this :

$f = fopen('/path/to/file', 'r');
if ($f) {
    while ($line = fgetcsv($f)) {  // You might need to specify more parameters
        // deal with $line.
        // $line[0] is the first column of the file
        // $line[1] is the second cokumn
        // ...
    }
    fclose($f);
} else {
    // error
}

(No tested, but example given on the manual page of fgetcsv should help you get started)


Of course, you'll have to get the correct path to the uploaded file -- see the $_FILE superglobal, and the section on Handling file uploads, for more informations about that.


And, to save the data into your database, you'll have to use the API which suits your DB engine -- if using MySQL, you should use either :

  • mysqli
    • Note that you should prefer mysqli, instead of the old mysql extension (which doesn't support features added in MySQL >= 4.1)
  • or PDO
Pascal MARTIN
Noted should be that getting the uploaded file is to be done by `$_FILES['fieldname']`.
BalusC
@Pascal Thanks that helps
Anand