When my client's are giving their inputs into the Excel file, they need the column header. But when they export the file into CSV (.csv) it includes the column heads into it. That's problem.
+---------+--------+-------------+
| Post id | Name | Designation |
+---------+--------+-------------+
101 noYon designer
102 nakib accountant
103 nishi developer
+---------+--------+-------------+
In my CSV (comma delimited) I got:
Post id,Name,Designation
101,noYon,designer
102,nakib,accountant
103,nishi,developer
I need to exclude the column heads (the first row) from the CSV when uploading it to MySQL using PHP.
Is there any way?
# Answer 1

A simple solution: read the first line and discard it before reading the rest of the file line by line in a loop:
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
fgetcsv($handle); // Discard first line. If we know the maximum line length
// add it as second argument: it's slightly faster
while( $data = fgetcsv( $handle) ) {
$query = mysqli->query( "INSERT INTO table (post_id,name,designation) VALUES ('".
implode($data,"','")."'";
}
A faster solution which I've not coded here: append multiple sets of values to the INSERT like this:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
# Answer 2
With assistance of
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r"); // read the file
?>
// make the loop and do upload
$find_header = 0; // a simple counter
while( $data = fgetcsv( $handle,6000,",","'") ) {
$find_header++; //update counter
if( $find_header > 1 ) {
$sql = mysql_query( "INSERT INTO table_name (
post_id,
name,
designation
)
VALUES
(
'".$data[0] ."',
'".$data[1] ."'
'".$data[2]."'
)
");
}
} // endwhile
The logic is very simple and a bit childish. If we know how fgetcsv() works. fgetcsv() is:
The fgetcsv() function parses a line from an open file, checking for CSV fields.
The fgetcsv() function stops returning on a new line, at the specified length, or at EOF, whichever comes first.
That means it fetches each line of the CSV each time the loop rounds. So if we pass a simple PHP counter and exclude the first line, then it's that simple.
And of course, don't forget to sanitize the data using PHP sanitizing functions like trim() or addslashes() etc. :)
You can get my whole bunch of codes
# Answer 3
$filename = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
fgetcsv($file);
while (($getData = fgetcsv($file, 10000, ",")) !== false){
echo "
";
print_r($getData);
echo "
";}
fclose($file);
}
这篇博客讨论了如何在使用PHP处理CSV文件时,跳过包含列头的第一行并将数据上传到MySQL数据库。作者提供了两种简单的方法:一种是读取文件并丢弃第一行,然后逐行插入数据;另一种是在插入语句中批量插入多个值,提高效率。同时,强调了在处理数据前进行数据清理的重要性。
4144

被折叠的 条评论
为什么被折叠?



