在csv中下载db记录但获取空行

时间:2016-11-01 07:33:18

标签: php mysql export-to-csv

伙计这个我的代码从mysql下载记录为csv但是在行中有逗号的任何值,它不下载,我得到一个空白行

这个解决方案可能是什么

这是我的代码

require_once('config.php');
$u =$_REQUEST['u'];
$cs =$_REQUEST['cs'];
$y =$_REQUEST['y'];
$d =$_REQUEST['d'];
$m =$_REQUEST['m'];
$date = "$y-$m-$d";
$todays = date("d-m-Y");
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=Mortgage-'.$u.'-Records-'.$date.'.csv');
//select table to export the data
$select_table=mysql_query("SELECT * FROM records WHERE  user ='".$u."' AND status ='".$cs."' AND DATE_FORMAT(posted, '%Y-%m-%d') = '$date'  ORDER BY id DESC");
$rows = mysql_fetch_assoc($select_table);
if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysql_fetch_assoc($select_table);
}

// get total number of fields present in the database
function getcsv($no_of_field_names)
{
$separate = '';


// do the action for all field names as field name
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\\r|\\n|,|"/', $field_name))
{
$field_name = '' . str_replace('', $field_name) . '';
}
echo $separate . $field_name;

//sepearte with the comma
$separate = ',';
}

//make new row and line
echo "\r\n";
}

非常感谢您的时间和帮助

1 个答案:

答案 0 :(得分:0)

更改代码的第一部分,如下所示:

require_once('config.php');
$u =$_REQUEST['u'];
$cs =$_REQUEST['cs'];
$y =$_REQUEST['y'];
$d =$_REQUEST['d'];
$m =$_REQUEST['m'];
$date = "$y-$m-$d";
$todays = date("d-m-Y");
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=Mortgage-'.$u.'-Records-'.$date.'.csv');
//select table to export the data
$select_table=mysql_query("SELECT * FROM records WHERE  user ='".$u."' AND status ='".$cs."' AND DATE_FORMAT(posted, '%Y-%m-%d') = '$date'  ORDER BY id DESC");

$i = 0;
while($rows = mysql_fetch_assoc($select_table);)
{
    if($i === 0) {
        getcsv(array_keys($rows));
    }

    getcsv($rows);
    $i++;
}

在函数getcsv中进行此更改 - 替换此代码:

$field_name = '' . str_replace('', $field_name) . '';

用这个:

$field_name = '"' . $field_name . '"';

但是不是使用mysql_query尝试实现PDO,因为mysql lib是对mysql注入的修剪,并且在新的php版本中将被弃用。