I am getting double output from a php loop
Question
My data is outputting twice and I am not to sure why. It should be one fname and lname per line.
<?php
$row = 1;
if (($handle = fopen("nameList1.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, " ")) !== FALSE) {
$num = count($data);
//$result = explode($data);
echo "<br />\n";
$row++;
for ($c=0; $c < $num; $c++) {
//echo $data[$c];
echo $data[0];
echo " ";
echo $data[1];
}
}
fclose($handle);
}
***** output ***********
Nancy AlvordNancy Alvord
Lucy HadacLucy Hadac
Laura LundgrenLaura Lundgren
Judy PigottJudy Pigott
Thomas BayleyThomas Bayley
Barbara BrownBarbara Brown
Aaron DixonAaron Dixon
Jennifer HadlockJennifer Hadlock
Molly AdolfsonMolly Adolfson
Susan AnsteadSusan Anstead
Shannon BraddockShannon Braddock
Isa D’ArleansIsa D’Arleans
Elizabeth DavisElizabeth Davis
William DonnellyWilliam Donnelly
Solution
for ($c=0; $c < $num; $c++) {
echo $data[0] . " " . $data[1];
}
As you have 2 differents data per line (fname, lname) $num is always equal to 2.
So twice, you will print out $data[0] & $data[1] ;)
You juste have to do :
echo $data[0];
echo $data[0];
Or if you absolutely want to use the for statement :
for ($c=0; $c < $num; $c++) {
echo $data[$c] . " ";
}
OTHER TIPS
try this
$row = 1;
if (($handle = fopen("nameList1.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, " ")) !== FALSE) {
$num = count($data);
//$result = explode($data);
echo "<br />\n";
$row++;
echo $data[0];
echo " ";
echo $data[1];
}
fclose($handle);
}
try this:
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
$record['contact_email'] = $data[2];
$record['subject'] = $_REQUEST['subject'];
$record['message'] = $_REQUEST['message'];
$record['status'] = 0;
$oAdminEmail->insertQueEmail($record);
}
} while ($data = fgetcsv($handle,1000,",","'"));
You are getting all the csv fields two times because , the forloop inside the while loop is starting from 0 to , it should be 1 to or 0 to
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow