简体   繁体   中英

PHP MySQL LOAD DATA INFILE Help

I just can't seem to get this query right. Basically I'm taking a csv from a form and trying to load it into the database. I took the majority of the query from phpmyadmin. i should be using the temp file right? here it is...

<form name = "price_chart" method="post" action="index.php?option=<?php echo $option ?>&task=complete" enctype="multipart/form-data">
<label>File: </label>
<input type="file" name="white" id="white"/><br />
<input type="hidden" value="TEST" name = "test" />
<input type="submit" name = "upload" value="Upload File" />
</form>

<?php
}
function complete($option){
$pfile = $_FILES['white']['name'];  
$ptmpName = $_FILES['white']['tmp_name'];
$test = $_POST['test'];
$result = mysql_query("LOAD DATA LOCAL INFILE '$ptmpName' REPLACE INTO TABLE 'jos_rates_table' FIELDS TERMINATED BY ',' ENCLOSED BY ' ' ESCAPED BY '\\' LINES TERMINATED BY '\n'('country' , 'rate')")or die ('Error: '.mysql_error ());
        while ($row = mysql_fetch_array($result)) {
        }
        $num_rows = mysql_num_rows($result);
        echo $num_rows;
}

UPDATE: Here's the Error message

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''jos_rates_table' FIELDS TERMINATED BY ',' ENCLOSED BY ' ' ESCAPED BY '\' LINES ' at line 1

You need to escape the slash for the lines terminated clause, otherwise you just added a newline to your query.

LINES TERMINATED BY '\\n'

Mysql will just get \n , but PHP tries to interpret those so you have to escape them.

You may have other issues, but you haven't told us what happens.

Not sure why are you using that long-ass url for action instead of index.php or just ''? Also I think you need to specify ENCTYPE="multipart/form-data" since it's an upload form for a file. Not sure how to just just insert the file, I think you need to get contents of the file, then explode it and do insert

$pfile = $_FILES['white']['name']; 
$ptmpName  = $_FILES['white']['tmp_name']; 
$fileSize = $_FILES['white']['size']; 
$fileType = $_FILES['white']['type']; 
$fp = fopen($ptmpName, 'r'); 
$content = fread($fp, $fileSize); 
$content = str_replace("\r\n", "\r", $content);
$Data_Lines = explode("\r",$content);

for ($n = 0; $n < (count($Data_Lines)-1);$n++){
$line =  addslashes($Data_Lines[$n]); 
$Value = explode(",",$line);
...//The you run insert  statements for $Value[1], $Value[2]...///

}

Or you can use fgetcsv - check this article: http://www.programmingfacts.com/import-csvexcel-data-mysql-database/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM