Page 1 of 1

php to .csv issue

Posted: Wed Aug 30, 2006 5:53 pm
by fitchic77
I have a script that runs fine, but if a name has an apostrophe..it throws off my csv file...

Code: Select all

include("../dsn.php");

function query_and_email($query, $email) {
	$result = mysql_query($query);// or return 'Query Failure Error: ' . mysql_error();
	$filename = time() . '.csv';
	$fp = fopen($filename, 'w'); //	or return 'File Opening Error: Could not open ' . $filename;
	
	while ($line = mysql_fetch_array($result, MYSQL_NUM)) {
	$output = '';
	$n = count($line);
		for ($i = 0; $i < $n; $i++) {
			if ($i > 0) {
			$output .= ',';
		}
		if (is_numeric($line[$i])) {
			$output .= $line[$i];
		} else {
			$output .=  $line[$i];
		}
		//echo str_replace($line[$i],",","") . "<br>";
}
	fwrite($fp, $output . "\r\n");
}
fclose($fp);

return '<table width=100% bgcolor=#FFFFFF><tr><td valign=top align=center>&nbsp;<br></td></tr><tr><td valign=top align=center><span class=bsmtxt>Reports</span></td></tr><tr><td valign=top align=center>&nbsp;<br></td></tr><tr><td valign=top align=center><table width=500 bgcolor=#FFFFFF><tr><td valign=top align=center>&nbsp;<br></td></tr><tr><td valign=top align=center><a href="'.$filename.'">'. $filename . '</a></td></tr><tr><td valign=top align=center>&nbsp;<br>&nbsp;<br>&nbsp;<br></td></tr></table></td></tr></table>';
}

echo query_and_email('SELECT upper(s.dcode) as Dealer_Code, d.name as Dealership_Name,  u.lname as Salesperson_Name, s.price as Price, s.name as Customer_Name, s.vocation as Vocation, s.serial as Serial, s.incentive as Incentive, s.redemption as Redemption_Type, s.cdate as Create_Date FROM sales s, users u, dealers d WHERE u.id = s.user_id AND UPPER(d.code) = UPPER(s.dcode)', 'email@domain.com');

Posted: Wed Aug 30, 2006 6:08 pm
by feyd
fputcsv() may be of interest.

If you're using PHP 4, look further down the page in the user comments for variants that may work.

Posted: Wed Aug 30, 2006 6:44 pm
by fitchic77
Thanks feyd!!

I know I didn't post my php right...I forgot...can you give me the construct again?

Posted: Wed Aug 30, 2006 7:08 pm
by feyd
[syntax=php]..[/syntax]
or
[syntax="php"]..[/syntax]