从PHP中的SQL结果下载CSV文件

时间:2017-03-18 11:16:50

标签: php csv

我想以SQL格式获取CSV查询的结果。我正在使用PHP。我的代码适用于结果,但我无法将列名称作为标题。请帮忙

@ $con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_error)
    die("Unable to connect to database : ".$con->connect_error);

$query = "SELECT * FROM User";
$result = $con->query($query);
$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    die;
}

1 个答案:

答案 0 :(得分:-1)

          if ( !empty( $_POST["tableName"]) ):
            if ( $columData = $db->cPanelAccess("SHOW COLUMNS FROM ".$_POST["tableName"])):
              ?>
              <tr class="header row">
              <?php
                while ($columName = $columData->fetch_assoc()):
                ?>
                  <td class="fieldNames"><?php echo $columName["Field"]; ?></td>
                <?php
                endwhile;
                ?>
                </tr>
              <?php
            endif;
          endif;

我使用类似的东西来打印表格标题