John Davidson

php to excel export data multiple rows

0 comments
Message:


I need to export php data to excel, but the point is that I need export multirows as how many there is in cart. But everytime all same rows like iphone 11 goes 5 times in 1 row.


output should be like this



MY Code:


$sql = "SELECT product_name, product_sku FROM `cart` WHERE `invoice_id` = '$inv'";  
$setRec = mysqli_query($conn, $sql);
$columnHeader = '';
$columnHeader = "title" . "\t" . "sku" . "\t";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {


//print_r($rec);
$rowData = '';

$sql2 = "SELECT qty FROM `cart` WHERE `product_sku` = '$rec[1]'";
$setRec2 = mysqli_query($conn, $sql2);

$rec2 = mysqli_fetch_row($setRec2);



//fetch all rows
foreach ($rec as $value) {


// multiple rows how many "qty"

for($i=0; $i<$rec2[0]; $i++) {

$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}}


$setData .= trim($rowData) . "\n";
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=User_Detail.xls");
header("Pragma: no-cache");
header("Expires: 0");
$setData = mb_convert_encoding($setData, 'HTML-ENTITIES', 'UTF-8');
echo ucwords($columnHeader) . "\n" . $setData . "\n";




My Answer:
It looks like you are on the right track with your code. However, there are a few things you can adjust to achieve the desired output of exporting multiple rows based on the quantity in the cart.

Here is an updated version of your code:

php
$sql = "SELECT product_name, product_sku FROM `cart` WHERE `invoice_id` = '$inv'";
$setRec = mysqli_query($conn, $sql);

$columnHeader = "title" . "\t" . "sku" . "\t";
$setData = '';

while ($rec = mysqli_fetch_row($setRec)) {
$sql2 = "SELECT qty FROM `cart` WHERE `product_sku` = '$rec[1]'";
$setRec2 = mysqli_query($conn, $sql2);
$rec2 = mysqli_fetch_row($setRec2);

for ($i = 0; $i < $rec2[0]; $i++) {
$rowData = '';
$rowData .= '"' . $rec[0] . '"' . "\t";
$rowData .= '"' . $rec[1] . '"' . "\t";
$setData .= $rowData . "\n";
}
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=User_Detail.xls");
header("Pragma: no-cache");
header("Expires: 0");

echo ucwords($columnHeader) . "\n" . $setData . "\n";


In this updated code, we are now looping through each product in the cart and creating a new row for each quantity of that product. This way, each product will have its own row in the Excel export based on the quantity in the cart.

Make sure to adjust the code as needed to fit your specific requirements and database structure.

Rate this post

4 of 5 based on 1917 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us