我想将csv加载到mysql中并管理单个字段。原始代码使用自动VALUES('','$ linemysql')上传内容;我怎么能把田地分开?我会查询:
$sql = "INSERT IGNORE INTO `database`.`table` (`field1`,field2`, `field3`, `field4`, `field5`) VALUES(`csvfield1`,csvfield2`, `csvfield3`, `csvfield4`, `csvfield5`);";
这是因为我可以管理哪一行将被包括在内 非常感谢
$lines = 0;
$queries = "";
$linearray = array();
$allLines = split($lineseparator,$csvcontent);
array_shift($allLines); // removes the 1st element
foreach($allLines as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto)
/* Change This query VALUES('','$linemysql'); */
$query = "INSERT IGNORE INTO `database`.`table` (`field1`,field2`, `field3`, `field4`, `field5`) VALUES('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n";
答案 0 :(得分:1)
使用PHP的内置CSV功能,包括fgetcsv()
。来自文档:
<?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);
}
?>
答案 1 :(得分:0)
您可以像这样修改您的查询
$query = "INSERT IGNORE INTO `database`.`table` (`field1`,field2`, `field3`, `field4`, `field5`) VALUES("'.$linemysql[0].'","'.$linemysql[1].'","'.$linemysql[2].'","'.$linemysql[3].'","'.$linemysql[4].'");";
由于