将MySQL查询导出为CSV时出错

时间:2012-10-04 02:06:39

标签: php mysql mysqli export-to-csv

我正在尝试使用PHP将数据导出到cdv / xls文件。我一直收到以下错误:

*“警告:mysql_query():提供的参数不是”*

中有效的MySQL-Link资源

这是我的代码:

<?php


//Connect the the database 
require('../mysql_connect.php') ;

$select = "SELECT * FROM customers WHERE email = 'info@example.com'";

$export = mysql_query ( $select, $dbc ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{
    $header .= mysql_field_name( $export , $i ) . "\t";
}

while( $row = mysql_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
{                                            
    if ( ( !isset( $value ) ) || ( $value == "" ) )
    {
        $value = "\t";
    }
    else
    {
        $value = str_replace( '"' , '""' , $value );
        $value = '"' . $value . '"' . "\t";
    }
    $line .= $value;
}
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                        
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";


?>

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我在mysql_connect.php中使用了mysqli而不是mysql。谢谢你的帮助!