I'm importing a csv file into a mysql table with php. Now I'm going to put some lines as I have in the csv. csv has no header.
I leave the script of how I created the table in mysql:
CREATE TABLE `Areceber` (
`Id` int NOT NULL AUTO_INCREMENT,
`N_utente` varchar(45) DEFAULT NULL,
`Ano` varchar(10) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
now I will put the html script:
<form method="post" action="conexaoexcel1.php" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" name="submit_file" value="Submit"/>
</form>
and now the page conexaoexcel1.php:
$file = $_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000, ";")) !== false)
{
foreach ($csv as $key => $value){
$Id = str_getcsv($value[0], ',');
var_dump($Id);
}
}
Now when I var_dump the first column it returns like this:
array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "2" } array(1) { [0]=> string(1) "3" } array(1) { [0]=> string(1) "4" } array(1) { [0]=> string(1) "5" } array(1) { [0]=> string(1) "6" } array(1) { [0]=> string(1) "7" } array(1) { [0]=> string(1) "8" } array(1) { [0]=> string(1) "9" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "2" }
Up to the line that has the number nine it returns fine, but when it starts on the line that has the number 10, it only returns the number 1 without the zero and so on. Can you help solve the problem?
CodePudding user response:
Your $csv
is already an array of data, and to output first column, use $csv[0]
without looping.
$file = $_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000, ";")) !== false)
{
$Id = $csv[0];
var_dump($Id);
}
Just check if your delimiter is right. If it's comma delimited change line
while(($csv = fgetcsv($file_open, 1000, ";")) !== false)
to
while(($csv = fgetcsv($file_open, 1000, ",")) !== false)
Otherwise it should work.