php to .csv issue

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
fitchic77
Forum Commoner
Posts: 51
Joined: Thu Jul 20, 2006 11:57 pm

php to .csv issue

Post 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');
Last edited by fitchic77 on Sat Oct 16, 2010 11:32 am, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
fitchic77
Forum Commoner
Posts: 51
Joined: Thu Jul 20, 2006 11:57 pm

Post by fitchic77 »

Thanks feyd!!

I know I didn't post my php right...I forgot...can you give me the construct again?
Last edited by fitchic77 on Sat Oct 16, 2010 11:25 am, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

[syntax=php]..[/syntax]
or
[syntax="php"]..[/syntax]
Post Reply