gpt4 book ai didi

php - 跳过导入 csv 的第一行

转载 作者:行者123 更新时间:2023-11-30 23:55:35 24 4
gpt4 key购买 nike

需要添加额外的一行以跳过 csv 文件中带有标题的第一行。但我不知道从哪里开始。

<?php

if(isset($_POST["submit"]))
{
$host="localhost"; // Host name.
$db_user="root"; //mysql user
$db_password=""; //mysql pass
$db='local'; // Database name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());

echo $filename=$_FILES["file"]["name"];
$ext=substr($filename,strrpos($filename,"."),(strlen($filename)-strrpos($filename,".")));

$file = fopen($filename, "r");
$handle = fopen("$filename", "r");
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE)
{
$import="INSERT into customers(fname,lname,company,address,city,state,country,postal_code,phone,email) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
else
{
print "<form enctype='multipart/form-data' method='post'>";
print "Type file name to import:";
print "<input type='file' name='file' id='file'>";
print "<input type='submit' name='submit' value='submit'></form>";
}
?>

感谢任何帮助。

最佳答案

考虑使用 SplFileObjectread CSV files ,它更好地支持迭代,例如结合标准 SPL LimitIterator,这是小菜一碟:

$file = new SplFileObject($filename);
$file->setFlags(SplFileObject::READ_CSV);
$it = new LimitIterator($file, 1);
foreach($it as $data) {
$mask = "INSERT INTO customers (fname, lname, company, address, city, state, country, postal_code, phone, email) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
$sql = vsprintf($mask, $data);
mysql_query($sql) or die(mysql_error());
}

另外请注意:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

关于php - 跳过导入 csv 的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13906813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com