W
W
webdeveloper482015-11-13 03:06:44
PHP
webdeveloper48, 2015-11-13 03:06:44

Error in foreach or PhpExcel?

Hello guys. I'm trying to export a table from the database to an xls file. Here is the code.
Everything works until the second foreach. Starting from the second foreach, the code does not work and breaks there. What's the problem? all.
dpaste - dpaste.com/21BHXTX (if suddenly the syntax hurts your eyes)

<?php

$link = mysqli_connect("localhost", "root", "", "");
mysqli_select_db($link, "blog");
$query = 'SELECT * FROM products';
$result = mysqli_query($link, $query);

if (isset ($_POST['export'])) {

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        foreach ($row as $k => $val) {
            $html = '<td>' . $val . '</td><br>';
            echo $html;
        }
    }
}

if (isset ($_POST['download'])) {

    require_once 'Classes/PHPExcel.php';
    require_once 'Classes/PHPExcel/Writer/Excel5.php';

    $xls = new PhpExcel();
    $xls->setActiveSheetIndex(0);
    $sheet = $xls->getActiveSheet();

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        $i = 0;

        foreach ($row as $ar) {
            $j = 0;
            //echo 'arr='.$arr;
            //echo 'j=';
            foreach ($ar as $val) {
               // echo 'arr=' . $val;exit();
                $sheet->setCellValueByColumnAndRow($j, $i, $val);
                $j++;
                //echo 'j=';//empty
                // echo 'val1='.$val;
            }
            $i++;
            //echo 'i='.$i;
        }
    }
    header("Expires: Mon, 1 Apr 1974 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    header("Content-type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=matrix.xls");

    $objWriter = new PHPExcel_Writer_Excel5($xls);
    $objWriter->save('php://output');
}
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<form method="POST">
    <button id="button" name="export" class="btn">Show table</button>
    <button id="button_dwn" name="download" class="btn">Download Table</button>
</form>
<table>
    <tbody>
    <tr></tr>
    </tbody>
</table>

</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2015-11-13
@znepok

Before the second while loop add mysql_data_seek($result, 0)

...
mysql_data_seek($result, 0);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
...

And I also believe that you can change the second if to else if:
else if (isset ($_POST['download'])) {

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question