doubi8512 2016-06-01 05:59 采纳率: 0%
浏览 37
已采纳

通过复选框选择,通过PHP将MySQL表导出为CSV

I need to display a list of results form a survey on a PHP page then export them to a CSV file. The list also acts as a summary that can be clicked thorugh to the full result.

I have all that sorted but now I need to have the CSV export by a check bx selection so that we dont need to download the entire databse each time just the ones we need.

My code so far below.

<div class="resultsList">

            <h1>PEEM Results List</h1>
            <a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
            <!-- Export CSV button -->
            <h3 class="resultsbydate">All results by date</h3>


                <div class="resultsListHeader">
                    <div class="clientidTab">Agency</div>
                    <div class="clientidTab">Family ID</div>
                    <div class="clientidName">Name</div>
                    <div class="clientidTab">Date</div>
                    <div class="clientidTab"></div>
                </div>
                <div class="entriesListMain">
                    <?php
                    $connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
                    $db = mysql_select_db("database_name", $connection); // Selecting Database
                    //MySQL Query to read data
                    $query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
                    while ($row = mysql_fetch_array($query)) {
                    echo "<div><input type=\"checkbox\" name=\"xport\" value=\"export\"><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
                    echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent&rsquo;s Review</strong></a></span>";
                    echo "<span><a href=\"peem-repsonses.php?id={$row['survey_id']}\"><strong>View Results</strong></a></span>";
                    echo "</div>";
                    }
                    ?>
                </div>
        </div>

        <?php
        if (isset($_GET['id'])) {
        $id = $_GET['id'];
        $query1 = mysql_query("select * from results where survey_id=$id", $connection);
        while ($row1 = mysql_fetch_array($query1)) {
        ?>

        <?php
        }
        }
        ?>

        <?php
        mysql_close($connection); // Closing Connection with Server
        ?>

And the downloadcsv.php

<?php
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);

$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');

$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
    $header[] = $row[0];
}   

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);

$query = "SELECT * FROM results";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
    fputcsv($fp, $row);
}
exit;
?>

Any help with this would be great, cheers

Updated with a screenshot of what I am trying to achieve enter image description here

  • 写回答

2条回答 默认 最新

  • doupiao9318 2016-06-05 05:08
    关注

    The initial result set needs to be wrapped in a form which POST to the next page. The Checkbox must send an array of ids to the export script.

    <input type='checkbox' name='xport[]' value='ID_OF_THE_ROW_HERE'>
    

    The [ ] after xport means that $_POST['xport'] will be an array of values.


    The export page can collapse that array of ids into a comma separated string and to be used the query:

    SELECT * FROM results WHERE id IN (4,7,11,30)
    

    <form method="POST" action="downloadcsv.php">
    
            <h1>PEEM Results List</h1>
            <a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
            <!-- Export CSV button -->
            <h3 class="resultsbydate">All results by date</h3>
    
    
                <div class="resultsListHeader">
                    <div class="clientidTab">Agency</div>
                    <div class="clientidTab">Family ID</div>
                    <div class="clientidName">Name</div>
                    <div class="clientidTab">Date</div>
                    <div class="clientidTab"></div>
                </div>
                <div class="entriesListMain">
                    <?php
                    $connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
                    $db = mysql_select_db("database_name", $connection); // Selecting Database
                    //MySQL Query to read data
                    $query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
                    while ($row = mysql_fetch_array($query)) {
                    echo "<div><input type='checkbox' name='xport[]' value='{$row['client_id']}'><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
                    echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent&rsquo;s Review</strong></a></span>";
                    echo "<span><a href=\"peem-repsonses.php?id={$row['survey_id']}\"><strong>View Results</strong></a></span>";
                    echo "</div>";
                    }
                    ?>
                </div>
    
             </form>
    

    Change $row['client_id'] to the correct value

    Then in the export script:

    <?php
    /*
    Expecting $_POST['xport'] array of row ids
    */
    if( !isset($_POST['xport']) OR !is_array($_POST['xport']) ) {
        exit('No rows selected for export');
    }
    
    $conn = mysql_connect("localhost","username","password");
    mysql_select_db("databasename",$conn);
    
    $filename = "peem_results.csv";
    $fp = fopen('php://output', 'w');
    
    $query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
    $result = mysql_query($query);
    while ($row = mysql_fetch_row($result)) {
        $header[] = $row[0];
    }   
    
    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename='.$filename);
    fputcsv($fp, $header);
    
    //Cast all ids to integer
    $ids = $_POST['xport'];
    array_walk($ids, function(&$value, $key) {
        $value = (int)$value;
    });
    
    $ids = implode(', ', $ids);
    
    $query = "SELECT * FROM results WHERE id IN ($ids)";
    $result = mysql_query($query);
    while($row = mysql_fetch_row($result)) {
        fputcsv($fp, $row);
    }
    exit;
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面