将MSSQL表信息导出到csv文件?

时间:2012-02-27 20:56:04

标签: php sql-server

我有一个MSSQL数据库表我正在PHP页面上访问。我正在使用SELECT ALL WHERE查询在页面上显示某些行。现在我需要一个按钮将SELECT ALL WHERE查询导出到.csv文件。我需要一些帮助才能开始这个。

我有一个功能来创建可以创建要导出的页面的页面:

public function SelectAllWhereFetch( $table, $where, $extra = "", $columns = "*" ) {
$tsql = "SELECT $columns FROM " . $table . " WHERE " . $where . $extra;
        $stmt = $this->ExecuteDontFreeQuery( $tsql );

        $result = mssql_query($query);

        // Checking for and creating table names
            $i = 0;
            echo '<html><body><table><tr>';
            while ($i < mssql_num_fields($result))
                {
            $meta = mssql_fetch_field($result, $i);
            echo '<td>' . $meta->name . '</td>';
            $i = $i + 1;
                }
        echo '</tr>';

        // Returning all rows in table
        while ( ($row = mssql_fetch_row($result))) 
            {
            $count = count($row);
            $y = 0;
            echo '<tr>';
            while ($y < $count)
                    {
                $c_row = current($row);
                echo '<td>' . $c_row . '</td>';
                next($row);
                $y = $y + 1;
                    }
            echo '</tr>';
                }
            mssql_free_result($result);

            echo '</table></body></html>';

    }

这是按钮操作的“if”语句:

if( $_REQUEST['exporting']) {

$vastreamline = $dataConnection->SelectAllWhereFetch("applicants",  
"loan_purpose='VA Streamline' AND statusdate >= '1/1/2011'", 
"ORDER BY statusdate DESC" );

        header("Content-type: text/x-csv");
        header("Content-Disposition: attachment; filename=streamline.csv");
        echo $vastreamline;
}

这是按钮操作:

 <div class="span3">
      <input type="hidden" name="exporting" value="true">
      <input type="submit" class="btn primary" value="Export CSV">
 </div>

我似乎正在建立与MSSQL数据库的连接,因为我可以显示信息。我只是弄清楚了获取按钮导出csv文件的语法。

1 个答案:

答案 0 :(得分:1)

由于您的按钮不在表单内,请尝试:

<form action="yourexportpage.php" method="POST">
    <div class="span3">
        <input type="hidden" name="exporting" value="true">
        <input type="submit" class="btn primary" value="Export CSV">
    </div>
</form>

还要将PHP导出页面更改为:

if( $_REQUEST['exporting']) {

    header("Content-type: text/x-csv");
    header("Content-Disposition: attachment; filename=streamline.csv");

    $dataConnection->SelectAllWhereFetch("applicants",  
    "loan_purpose='VA Streamline' AND statusdate >= '1/1/2011'", 
    "ORDER BY statusdate DESC" );
}