使用PHP将数据从SQl导出到Excel

时间:2011-07-25 15:55:25

标签: php mysql excel

因此管理员可以选择通过选择存储在col []中的复选框来选择要导出到excel的内容... 这是我的导出代码

 session_start();
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DB = 'fyp_db';

$link = mysqli_connect($HOST, $USERNAME, $PASSWORD, $DB);

if (is_array($_POST['col'])) {
    $sql = "SELECT ";
    foreach ($_POST['col'] AS $value) {
        $sql .= "{$value}, ";
    }
    $sql = substr($sql, 0, -2);
    $sql .= " FROM account, coursedetail, coursecategory";  
    /*echo "sql= " . $sql . "<br /><br />\n";*/
} else {
    echo "No column was selected<br /><br />\n";
}

function cleanData(&$str) { $str = preg_replace("/\t/", "\\t", $str); $str = preg_replace("/\r?\n/", "\\n", $str); if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; }

$filename = "website_data.xls"; 
header("Content-Type: text/plain"); 
$flag = false; 
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
while(false !== ($row = mysql_fetch_assoc($result))) { 
    if(!$flag) { 
    // display field/column names as first row 
    echo implode("\t", array_keys($row)) . "\r\n"; 
    $flag = true; 
        } 
        array_walk($row, 'cleanData'); 
        echo implode("\t", array_values($row)) . "\r\n"; 

        }

我得到了错误..

警告:mysql_fetch_assoc()要求参数1为资源,对象 C:\ xampp \ htdocs \ project \ export_successful.php 28行中给出

为什么呢? :(

1 个答案:

答案 0 :(得分:2)

你正在混淆mysqli和mysql调用。这两个库不兼容,并且一个库返回的句柄/语句不能在另一个库中使用。

$result = mysqli_query($link, $sql) or die(mysqli_error($link));
               ^--- note the 'i'
while(false !== ($row = mysql_fetch_assoc($result))) { 
                             ^--- note the LACK of an 'i'