这个csv到mysql上传有什么问题?

I built this script to upload .csv files and directly send them to my database. But it doesn't write anything into my table. If i uploade the file to my server and write "file.csv" instead of "$file" it works perfectly.. But I want to upload them via form. Can anyone help me?

Form:

<html> 
<head> 
</head> 
<body> 

<h2> CSV Import </h2> 
<form>
 <form method="post" action="imp.php" enctype="multipart/form-data"> 
  <input type="file" name="file" /> 
  <br /> 
  <input type="submit" name="submit" value="Submit" /> 
</form>
</body> 
</html>

imp.php:

<?php
$delimiter = ',';

$db = new mysqli('host', 'user', 'pw', 'db');


$file= $_FILES[file][temp_name];


if (($handle = fopen($file, 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
        foreach($data as $i => $content) {
            $data[$i] = $db->real_escape_string($content);
        }
        $db->query("INSERT INTO table VALUES('" . implode("','", $data) . "');");
    }
    fclose($handle);
}


?>

It's $_FILES['file']['tmp_name']

See http://www.php.net/manual/en/features.file-upload.post-method.php

ie not temp_name

I would strongly suggest using LOAD DATA INFILE syntax since you have a well-structured CSV on your server to being with.

Something like:

LOAD DATA LOCAL INFILE '/path/to/local/file'
INTO TABLE table
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '
'

This will allow you to upload all content with a single query. Also note that if your MySQL server and application server are on the same machine, you would be able to omit the LOCAL option as MySQL could reads the file directly from the file system at the path specified (assuming it has permissions).

This eliminates the need to open the file and iterate through it.

If you do not want to go this routes, I would at least suggest doing bulk inserts and adding multiple rows at a time (rather than having a single insert query for each row).