Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question