可以将多表MySQL结果下载到.csv

时间:2013-09-03 12:35:13

标签: php mysql csv export-to-csv

我正在使用PHP和MySQL。我试图从我的数据库中的2个表运行MySQL查询,然后将结果下载到CSV。当我通过phpMyAdmin运行MySQL查询时,结果是我正在寻找的,但当我运行php页面时,我收到一个错误:

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /..../..../...../workingpage.php on line 26

显然,没有给出结果,运行.php程序/页面时我得到一个空白的.csv文件。自上周四以来,我每天都在修补这一点,并且非常感谢任何指导或帮助。这是我到目前为止所拥有的。

    <?php
    include("includes/credentials.inc");

    $con = mysqli_connect($host, $user, $password, $database)
           or die ("COULDN'T CONNECT TO MY SQL SERVER");


    $query = "SELECT (

    SELECT CONCAT( manufacturer,  '-', partnumber ) AS sku
    )sku, weight, sell
    FROM  `amz_parts` 
    INNER JOIN  `amz_mfg` ON amz_mfg.`mfr-code` = amz_parts.`mfr-code`)";



    $result = mysqli_query($con, $query); 

    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    function maybeEncodeCSVField($result) {
        if(strpos($result, ',') !== false || strpos($result, '"') !== false ||                                 strpos($result, "\n") !== false) {
    $result = '"' . str_replace('"', '""', $result) . '"';
        }
        return $result;
    }

    while ($row = mysqli_fetch_array($result)) {
        echo "$row[0] $row[1] $row[2]\n";}
    ?>

1 个答案:

答案 0 :(得分:0)

最后不应该在amz_parts上。mfr-code)“;

$query = "SELECT (

    SELECT CONCAT( manufacturer,  '-', partnumber ) AS sku
    )sku, weight, sell
    FROM  `amz_parts` 
    INNER JOIN  `amz_mfg` ON amz_mfg.`mfr-code` = amz_parts.`mfr-code`";