Jump to content

Export php table to excell..


moudyboy

Recommended Posts

I am new in programing. would like some help this is my cart.php file and i would like to export the cart contents into excel...after a user presses a submit button..

 

Please Please help...thanks

 

This is my code so far:-

 

<?php
session_start();
if (!isset($_SESSION["customer"])) {
    header("location: customer_login.php"); 
    exit();
}
//error script
error_reporting(E_ALL);
ini_set('display_errors','1');
//connect to the database
include "../storescripts/connect_to_mysql.php";
?>
<?php
///////////////////////////////////////////////////////////////////////////////////
//					SECTION ONE
///////////////////////////////////////////////////////////////////////////////////
if(isset($_POST['pid'])){
$pid=$_POST['pid'];
$wasFound=false;
$i=0;

//if the cart session is set or empty
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"])< 1){
//Runs if the cart is empty
$_SESSION["cart_array"]= array(0 => array("item_id"=>$pid,"quantity"=>1));	
}else{
//Runs if the cart has at least one item in it
foreach($_SESSION["cart_array"] as $each_item){
 $i++;
while(list($key,$value)= each($each_item)){
if($key == "item_id"&&$value==$pid){
//the ite is in the cart..hence we adjust the quantity
array_splice($_SESSION["cart_array"],$i-1,1,array(array("item_id"=>$pid,"quantity"=>$each_item['quantity']+1)));
$wasFound=true;
}//close if conditio
   }//close while loop
  }//close foreach loop
  if($wasFound==false){
  array_push($_SESSION["cart_array"],array("item_id"=>$pid,"quantity"=>1));
}
  }
  header("location: cart.php");
}
?>
<?php
///////////////////////////////////////////////////////////////////////////////////
//					SECTION TWO
///////////////////////////////////////////////////////////////////////////////////
//if usser chooses to empty their sopping cart
if(isset($_GET['cmd'])&& $_GET['cmd']=="emptycart"){
   unset($_SESSION["cart_array"]);
   }
?>
<?php
///////////////////////////////////////////////////////////////////////////////////
//					SECTION THREE
///////////////////////////////////////////////////////////////////////////////////
//if usser chooses to empty their sopping cart
if(isset($_POST['item_to_adjust'])&& $_POST['item_to_adjust']!=""){
	//execute some code
	$item_to_adjust=$_POST['item_to_adjust'];
	$quantity=$_POST['quantity'];
	$quantity=preg_replace('#[^0-9]#i', '',$quantity);
	if($quantity >= 1000){$quantity=999;}
	if($quantity < 1){$quantity= 1;}
	$i=0;
foreach($_SESSION["cart_array"] as $each_item){
 $i++;
while(list($key,$value)= each($each_item)){
if($key == "item_id"&&$value==$item_to_adjust){
//the ite is in the cart..hence we adjust the quantity
array_splice($_SESSION["cart_array"],$i-1,1,array(array("item_id"=>$item_to_adjust,"quantity"=>$quantity)));
}//close if conditio
   }//close while loop
  }//close foreach loop
}
?>
<?php
///////////////////////////////////////////////////////////////////////////////////
//					SECTION FOUR
///////////////////////////////////////////////////////////////////////////////////
if(isset($_POST['index_to_remove'])&&$_POST['index_to_remove']!=""){
	//access the array and run code to remove
$key_to_remove= $_POST['index_to_remove'];
if(count($_SESSION["cart_array"])<=1){
unset($_SESSION["cart_array"]);
}else{
unset($_SESSION["cart_array"]["$key_to_remove"]);
sort($_SESSION["cart_array"]);
}
}
?>
<?php
///////////////////////////////////////////////////////////////////////////////////
//					SECTION FIVE
///////////////////////////////////////////////////////////////////////////////////

$cartOutput="";
$cartTotal="";
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"])< 1){
   $cartOutput="<h2 align='center'>Your Cart Is Empty</h2>";
}else{
$i=0;
foreach($_SESSION["cart_array"] as $each_item){
$item_id=$each_item['item_id'];
$sql=mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
while($row=mysql_fetch_array($sql)){
	$product_name=$row["product_name"];
	$price=$row['price'];
	$details=$row['details'];
}
	$pricetotal= $price*$each_item['quantity'];
	$cartTotal=$pricetotal + $cartTotal;

    //setlocale(LC_MONETARY,"en_KSHs");
	//$pricetotal= money_format("%10.2n", $pricetotal);
	//dynamic table assembly

	$cartOutput .="<tr align='center'>";
	$cartOutput .='<td><a href="../home.php?id=' . $item_id . '">' .$product_name . '</a><br/><img src="../inventory_images/' . $item_id . '.jpg" alt="' . $product_name . '" width="40" height="52" border="1"/></td>';
	$cartOutput .='<td>' . $details . '</td>';
	$cartOutput .='<td><form action="cart.php" method="post">
	<input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="3" />
	<input name="adjustBtn' . $item_id . '" type="image" value="change" src="../images/buttons/button_save.gif"/>
	<input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
	</form></td>';
	//$cartOutput .='<td>' . $each_item['quantity'] . '</td>';
	$cartOutput .='<td>' . $price . '</td>';
	$cartOutput .='<td>' . $pricetotal . '</td>';
	$cartOutput .='<td><form action="cart.php" method="post">
	<input name="deleteBtn' . $item_id . '" type="image" value="X" src="../images/buttons/button_delete.gif"/>
	<input name="index_to_remove" type="hidden" value="' . $i . '" /
	></form></td>';
	$cartOutput .='</tr>';
	$i++;
}

  $cartTotal="<div align='right'>Your Total is KSHs. ".$cartTotal."</div>";
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Your Cart</title>
<link rel="stylesheet" href="../style/style.css" type="text/css" media="screen"/>
</head>
<body>
<div align="center" id="mainWrapper">
  <?php include_once("../templates/template_header3.php");?>
  <div id="pageContent">
  <div style="margin:24px;text-align:left;">
  <br/>
  <table width="100%" border="1" cellspacing="0" cellpadding="6">
    <tr bgcolor="#00FF66"  align="center">
      <td width="17%" bgcolor="#5BD7D7"><strong>Product</strong></td>
      <td width="50%" bgcolor="#5BD7D7"><strong>Product Details</strong></td>
      <td width="7%" bgcolor="#5BD7D7"><strong>Quantity</strong></td>
      <td width="9%" bgcolor="#5BD7D7"><strong>Unit Price<br/>(KHSs.)</strong></td>
      <td width="10%" bgcolor="#5BD7D7"><strong>Total<br/>(KHSs.)</strong></td>
      <td width="7%" bgcolor="#5BD7D7"><strong>Remove</strong></td>
    </tr>
    <?php echo $cartOutput; ?>
<!--     <tr>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
    </tr> -->
  </table>
  <?php echo $cartTotal; ?><br/>
  <br/>
  <a href="cart.php?cmd=emptycart">Empty Your Cart</a><br/>
</div>
</div>
<?php include_once("../templates/template_footer.php");?>
</div>
  </body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/225527-export-php-table-to-excell/
Share on other sites

this is what i use. this will export the whole table.

if you want custom export then just change the query.

 

if you use _post you can create a custom query.

hope this helps

 

<?php
include("config.php"); 
$table = 'table_name';
$file = 'export';

$link = mysql_connect($host, $username, $password) or die("Can not connect." . mysql_error());
mysql_select_db($db_name) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
// header( "Content-disposition: filename=".$filename.".csv");
header( "Content-disposition: attachment; filename=".$filename.".csv");
print $csv_output;
exit;
?>

Yap am English, but am currently in Malaysia...

 

The query that i want passed on is the one which is be generated by the array....the one which is being displayed in section 5 of my code....i want to export what is being displayed(the output) in section 5..

 

Thanks again..

upload this.

change line 5. remove input_test_id with a real id.

goto the page and see if ut exports what u want.

 

<?php
include "../storescripts/connect_to_mysql.php"; 
//$table = 'dsgi_serval ';
$file = 'export';
$item_id = 'input_test_id';

$link = mysql_connect($host, $username, $password) or die("Can not connect." . mysql_error());
mysql_select_db($db_name) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT ");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
// header( "Content-disposition: filename=".$filename.".csv");
header( "Content-disposition: attachment; filename=".$filename.".csv");
print $csv_output;
exit;
?>

I did this it exported once and it then kept on telling me:

 

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\al-usul2\customer\cart.php:142)--

 

which is the line: if(isset($_POST['cmd'])&& $_POST['cmd']=="export"){ in the code below

 

<?php 
$file = 'export';
$item_id = 'item_id';
$csv_output = "";

if(isset($_POST['cmd'])&& $_POST['cmd']=="export"){
include "../storescripts/connect_to_mysql.php"; 
//$table = 'dsgi_serval ';
$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
$i = 0;
if (mysql_num_rows($sql) > 0) {
while($row=mysql_fetch_array($sql)){
	$product_name=$row["product_name"];
	$price=$row['price'];
	$details=$row['details'];
}
	$pricetotal= $price*$each_item['quantity'];
	$cartTotal=$pricetotal + $cartTotal;

	$csv_output  .="<tr align='center'>";
	$csv_output .='<td><a href="../home.php?id=' . $item_id . '">' .$product_name . '</a><br/><img src="../inventory_images/' . $item_id . '.jpg" alt="' . $product_name . '" width="40" height="52" border="1"/></td>';
	$csv_output  .='<td>' . $details . '</td>';
	$$csv_output .='<td><form action="cart.php" method="post">
	<input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="3" />
	<input name="adjustBtn' . $item_id . '" type="image" value="change" src="../images/buttons/button_save.gif"/>
	<input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
	</form></td>';
	//$cartOutput .='<td>' . $each_item['quantity'] . '</td>';
	$csv_output  .='<td>' . $price . '</td>';
	$csv_output  .='<td>' . $pricetotal . '</td>';
	$csv_output  .='<td><form action="cart.php" method="post">
	<input name="deleteBtn' . $item_id . '" type="image" value="X" src="../images/buttons/button_delete.gif"/>
	<input name="index_to_remove" type="hidden" value="' . $i . '" /
	></form></td>';
	$csv_output  .='</tr>';
	$i++;
}
}
$csv_output .= "\n";

$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 6 ");
while ($rowr = mysql_fetch_row($sql)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
// header( "Content-disposition: filename=".$filename.".csv");
header( "Content-disposition: attachment; filename=".$filename.".csv");
print $csv_output;
exit();

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.