php - inserting .csv file to mysql db starting from 2nd row -
php - inserting .csv file to mysql db starting from 2nd row -
i trying upload .csv file user can browse file , upload file , info gets inserted mysql db.but 1st row of .csv file getting inserted in table row contain column names respectively.here code
<?php //connect database if (isset($_post['submit'])) { if (is_uploaded_file($_files['filename']['tmp_name'])) { echo "<h1>" . "file ". $_files['filename']['name'] ." uploaded successfully." . "</h1>"; } //import uploaded file database $handle = fopen($_files['filename']['tmp_name'], "r"); while (($data = fgetcsv($handle, 1000, ",")) !== false) { //db connection $import="insert csv(id,user,phone) values('$data[0]','$data[1]','$data[2]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); print "import done"; }else { echo "sorry"; } ?>
my table structure
create table `csv` ( id int(10) not null default '0', user varchar(10) not null, phone int(10) not null ) engine=innodb default charset=latin1
$handle = fopen($_files['filename']['tmp_name'], "r"); fgetcsv($handle, 1000, ","); // pop headers while (($data = fgetcsv($handle, 1000, ",")) !== false) ...
just phone call fgetcsv
1 time before start looping through rest.
in fact, utilize idiom:
$fh = fopen(...); $headers = fgetcsv($fh); while ($row = fgetcsv($fh)) { $row = array_combine($headers, $row); echo $row['columnname']; }
it allows access columns name, instead of index.
php mysql csv
Comments
Post a Comment