开发者

Remove occurances of ",,," from MySQL Database Output PHP

I am outputting the contents of my MySQL Database into a text file using the below code:

<?php
$host = 'localhost';
$user = 'myusername';
$pass = 'mypassword';
$db = 'mydbname';
$table = 'mytablename';
$file = 'outputfilename';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
//$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].",";
}
$csv_output .= "\n";
}
//echo $csv_output;
$myFile = "output.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $csv_output;
fwrite($fh, $stringData);
fclose($fh);
exit;
?>

However I would like to know how I could 开发者_如何学Goreplace the occurances of the string ",,," with this: "," before it goes into the text file.


No need for preg_replace().

A simple str_replace will suffice.

$stringData = str_replace(',,,', ',', $csv_output);


problem is in:

$values = mysql_query("SELECT * FROM ".$table."");

if you got ,,,, it means that some columns has no value. Detect those columns, do not include them in SELECT statement.

if you will automatically (preg_replace, str_replace) change multiple commas to one comma, you are on good way to corrupt CSV file.


Use preg_replace(). Something like this (untested):

$pattern = '/\,\,\,/';
$replacement = ',';
echo preg_replace($pattern, $replacement, $stringData);


add this code:

while ($csv_output=str_replace(',,', ',', $csv_output)) echo '.';

OR change the for code:

for ( $j=0; $j<$i; $j++) {
    $csv_output .= (isset($rowr[$j])) ? $rowr[$j]."," : '';
}


str_replace()

$stringData = str_replace(',,,', ',', $stringData);

http://php.net/str-replace

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜