3

i know how to upload a csv file into mysql database but only through cmd. i want to know how to upload csv file into mysql database using php form and will disregard some information on the excel and will only start importing starting from a certain line. ? kindly help me.

1
  • I know you said you can do it from the cmd line and need to load certain info (specific fields?) and starting from a certain line - load data infile permits this functionality.. and allows fields to have the results of expressions calculated at import time to be loaded. It's way faster than individual row insertions provided you can manipulate the data correctly of course. Commented Mar 14, 2012 at 7:04

5 Answers 5

6

(PHP 4, PHP 5)

fgetcsv

See php manual http://php.net/manual/en/function.fgetcsv.php

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
Sign up to request clarification or add additional context in comments.

3 Comments

I think question is upload csv direct to database... like with some command in exec function...
@Saiyam Patel Read question carefully .."i know how to upload a csv file into mysql database but only through cmd. i want to know how to upload csv file into mysql database using php"
will these work if the important data starts from row 10 and the previous rows contains information but they are not really that important,so the importing has to skip rows 1-9 and starts only from row 10? thanks
2

Try this it's working well, you can add as many values as possible depending on the number of columns you have in the CSV file. Then in the HTML code put the uploading syntax in the tag.

**

$fname = $_FILES['csv_file']['name'];     
$chk_ext = explode(".",$fname);             

        $filename = $_FILES['csv_file']['tmp_     name'];   
$handle = fopen($filename, "r");      
if(!$handle){
die ('Cannot open file for reading');
}      
              while (($data = fgetcsv($handle,     10000, ",")) !== FALSE)
{
          $query = "INSERT INTO tablename       (col1_csv, col2_csv)
values ('$data[0]', '$data[1]');
mysql_query($query) or die(mysql_error    ());
}
 fclose($handle);
?>

**

3 Comments

but it does not say that i can skip a few rows before importing.
Skip a few rows? Inside the CSV you are uploading or you have a record there that you'll need to overwrite so that it does not appear twice. If that is the case you can apply DUPLICATE in the mysql query.
no, for example the data that needs to be imported will start in row number 10 since rows 1-9 are insignificant text.
1

You can use the MySQL LOAD DATA INFILE statement to bulk-insert thousands of records at once. PHP can handle the file upload. The PHP code would be something similar to:

$query = sprintf("
    LOAD DATA LOCAL INFILE '%s'
    INTO TABLE `table1`
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
    LINES TERMINATED BY '\\r\\n'
    IGNORE 1 LINES
    ",
    mysql_real_escape_string($FILES["file1"]["tmp_name"])
);

The LOCAL keyword should allow you to workaround some security restrictions. Change the FIELDS TERMINATED BY and LINES TERMINATED BY parameter to match the separators used by excel while exporting. IGNORE 1 LINES tells MySQL to skip the header row(s).

Note: Excel does not seem to use an escape character; but it will (i) enclose the fields that contain , and " with " (ii) use "" to escape a single " inside data. I believe MySQL will understand this encoding and import the data correctly.

2 Comments

hi i used your php script and it worked, i modified it a bit. however, how would i able to check if one data is already in the database so that if the user accidentally selected the same csv file, an error will pop and inform him that some data are already in the database. thanks.
i used the ignore or replace keyword somewhere in the statement. thanks
0

You could use the "LOAD DATA INFILE " statement with the " IGNORE ... LINES " option which you can use from the command line as well as from PHP.

Comments

0

try this:

 $filename=$_FILES["upload_file"]["name"];
 $extension = end(explode(".",$filename));
 if ($extension=='csv') {
     $tmp_file=$_FILES["upload_file"]["tmp_name"];
     $handle = @fopen($tmp_file, "r");
     //specify your own database connection parameter
     $db = new PDO('mysql:host=localhost;dbname=demo','user','password');
     $stmt = $db->prepare("INSERT INTO writers (writer_name, writer_email) VALUES (?, ?)");
     if ($handle) {
        while (($buffer = fgets($handle, 4096)) !== false) {
            $array=explode(",",$buffer);
            $count=1;
            foreach ($array as $value) {
                $stmt->bindParam($count, $value);
                $count++;
            }
            $stmt->execute();
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
        }
        $db = null;
        echo "<p>Success</p>";
    }
    else {
        $error="<p style='color:red;'>Invalid file type</p>";
    }

Refer to http://pradipchitrakar.com.np/programming/upload-csv-mysql-php/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.