Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading my lines of a csv file

Status
Not open for further replies.

someoneneedshelps

Technical User
Mar 3, 2016
75
GB
Hi
Hit a brick wall with this function, it does what I want but one line, I need it to read my lines of data, can anyone help please?

Code:
	function mysql_insert_array($table, $column_list, $filename, $types) 
	{	
		$i=0;
		$f = fopen($filename, "r");
		while (($line = fgetcsv($f)) !== false) 
		{				
			$row = $line[0];    // We need to get the actual row (it is the first element in a 1-element array)
			$cells = explode(";",$row);	
			$type = explode(";",$types);
			foreach ($cells as $cell) 
			{				
				//case staement to find values types ie; int text etc
				$myresult = switch_to_get_values($type[$i],$cell);
				if($myresult)
					$fields[] = "'" . htmlspecialchars($cell) . "'";
				else
					$fields[] = $cell;
				$i++;
			}			
			$value_list = join(',', str_replace("' ","'",$fields));
			$query = "INSERT INTO " . $table . " (" . $column_list . ") VALUES (" . $value_list . ")";
		}		
		fclose($f);						
		
	return $query;
	}
 
So what is not working exactly?

This line
while (($line = fgetcsv($f)) !== false)
gets one line of the csv file at a time as an array.

So this line:
$row = $line[0];
Is basically setting $row to the first value of your of the first line of your CSV file.

Which you then try to explode and since its not a semi-colon separated list of values, does nothing to it so $cells will just be equal to $row.

Not sure that is what you are trying to do.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Ive done it, how do you mark these solved?

Code:
$fileData=fopen($filename,'r');
	while($row=fgets($fileData))
	{  
		$data_array = explode(",",$row);
		foreach($data_array as $columns=>$value)
		{
			echo "<br>" .$value;
		}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top