我尝试将包含完整数据的CSV文件导入phpMyAdmin数据库表。但是,只导入CSV文件中的部分数据。如果我在phpMyAdmin导入CSV文件,则导入所有数据。没有错误显示,我不太确定问题出现在哪里。我使用LOAD DATA INFILE将数据加载到数据库表中。
这是我的代码:
<?php
session_start();
$host = "localhost";
$user = "root";
$password = "";
$db = "smposi";
$con = mysqli_connect($host,$user,$password,$db);
$message = "";
$m_sfile = $_SESSION['sfile'];
if (isset($_POST['submit']))
{
$allowed = array('csv');
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed))
{
// show error message
$message = 'Invalid file type, please use .CSV file!';
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "Imported CSV/" .
$_FILES['file']['name']);
$file = "Imported CSV/" . $_FILES['file']['name'];
$query = <<<eof
LOAD DATA LOCAL INFILE '$file'
INTO TABLE $m_sfile
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(sdate2,sdate,location,pcode,code,custarea,
pdesc,packet,weight,max,ppacket,lqty,printed,
corder,luserid,ltime)
eof;
$query2 = mysqli_query($con,"DELETE FROM $m_sfile WHERE
location=''");
if (!$result = mysqli_query($con, $query))
{
exit(mysqli_error($con));
}
$message = "CSV file successfully imported!";
}
}
?>
答案 0 :(得分:1)
我使用以下简单脚本导入了CSV数据。如果这有帮助,请尝试一下。另请阅读complete article以便轻松导入/导出CSV数据。
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$sql = "INSERT into employeeinfo (emp_id,firstname,lastname,email,reg_date)
values ('".$getData[0]."','".$getData[1]."','".$getData[2]."','".$getData[3]."','".$getData[4]."')";
$result = mysqli_query($con, $sql);
if(!isset($result))
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"index.php\"
</script>";
}
else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"index.php\"
</script>";
}
}
fclose($file);
}
}
?>
答案 1 :(得分:0)
尝试运行以下代码。
<?php
$databasehost = "localhost";
$databasename = "smposi";
$databasetable = "sample";
$databaseusername="test";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "filename.csv";
if(!file_exists($csvfile)) {
die("File not found. Make sure you specified the correct path.");
}
try {
$pdo = new PDO("mysql:host=$databasehost;dbname=$databasename",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator));
echo "Loaded a total of $affectedRows records from this csv file.\n";
?>