PHP - Please Help: Export Csv From Php Table Not Working
Hi all - new here so please be gentle!
I have a html table generated from php and am using a script I found on the net to export it to csv. The problem is, the exported csv file stops at the 2nd column and never starts a new row, plus has an empty column at the end. Obviously i want several rows (depending on the mysql query used to populate the table, it could be tens of rows long.) Is any one please able to help me shed some light as to what's going wrong? Thanks <table class="statistics"> <thead> <tr><th> Name </th><th> </th><th> Date </th></tr> </thead> <tbody> <?php if( $page['reportByDate'] ) { ?> <?php foreach( $page['reportByDate'] as $row ) { ?> <tr> <td><?php echo $row['name'] ?></td> <td><?php echo $row['email'] ?></td> <td><?php echo $row['date'] ?></td> </tr> <?php } ?> <?php } else { ?> <?php } ?> </tbody> </table> <?php } ?> <? $csv_hdr = "Name, Email, Date"; $csv_output .= $row['name'] . ", "; $csv_output .= $row['email'] . ", "; $csv_output .= $row['date'] . ", "; $csv_output .= $row['value'] . "\n"; //ensure the last column entry starts a new line ?> <? ?> <br /> <center> <form name="export" action="export.php" method="post"> <input type="submit" value="Save as CSV"> <input type="hidden" value="<? echo $csv_hdr; ?>" name="csv_hdr"> <input type="hidden" value="<? echo $csv_output; ?>" name="csv_output"> </form> </center> <?php /* This file will generate our CSV table. There is nothing to display on this page, it is simply used to generate our CSV file and then exit. That way we won't be re-directed after pressing the export to CSV button on the previous page. */ //First we'll generate an output variable called out. It'll have all of our text for the CSV file. $out = ''; //Next we'll check to see if our variables posted and if they did we'll simply append them to out. if (isset($_POST['csv_hdr'])) { $out .= $_POST['csv_hdr']; $out .= "\n"; } if (isset($_POST['csv_output'])) { $out .= $_POST['csv_output']; } //Now we're ready to create a file. This method generates a filename based on the current date & time. $filename = $file."_".date("Y-m-d_H-i",time()); //Generate the CSV file header header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header("Content-disposition: filename=".$filename.".csv"); //Print the contents of out to the generated file. print $out; //Exit the script exit; ?> Similar TutorialsHello All, I am currently working on export to pdf, below is the code, i am able to see the data is getting retrieved from mysql table. I am having 2 issue: 1. When data is getting retrieved one column is on left corner it's now showing the data as it's Sno it gets hidden from left corner. 2. Second issue when i click on the link it's just adding a # tag on the url nothing else.
Please guide me to fix the code.
<!DOCTYPE html> <html> <head> <Title> Export Supplier / Visiters Details</Title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/> <script type="text/javascript" src="tableExport.js"></script> <script type="text/javascript" src="jquery.base64.js"></script> <script type="text/javascript" src="html2canvas.js"></script> <script type="text/javascript" src="jspdf/libs/sprintf.js"></script> <script type="text/javascript" src="jspdf/jspdf.js"></script> <script type="text/javascript" src="jspdf/libs/base64.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </head> <?php $con=mysqli_connect("localhost", "root", "", "cvmsdb"); $qry="SELECT * FROM tblsupvisitor"; $result=mysqli_query($con, $qry); $records = array(); while($row = mysqli_fetch_assoc($result)){ $records[] = $row; } ?> <div class="row" style="height:300px;overflow:scroll;"> <table id="tblsupvisitor" class="table table-striped"> <thead> <tr class="warning"> <th>SNO.</th> <th>Full Name</th> <th>Mobile Number</th> <th>Address</th> </tr> </thead> <tbody> <?php foreach($records as $rec):?> <tr> <td><?php echo $rec['ID']?></td> <td><?php echo $rec['FullName']?></td> <td><?php echo $rec['MobileNumber']?></td> <td><?php echo $rec['Address']?></td> </tr> <?php endforeach; ?> </tbody> </table> </div> <li><a href="#" onclick="$('#tblsupvisitor').tableExport({type:'json',escape:'false'});"> <img src="images/icon/logo.png" width="24px"> Export to Pdf</a></li> <li><a href="#" onclick="$('#tblsupvisitor').tableExport({type:'json',escape:'false'});"><img src="images/icon/logo.png" width="24px">JSON (ignoreColumn)</a></li> </html>
Kind Regards, Naveed. Hi i am new in PHP...have a project and have stuck...please please help.... I have a cart and i need to export the cart contents to excell...here is my code...please take a look and see if u can hepl... I also need to have an export button...and wen pressed the cart will be exported to excell thanks... <?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/> <a href="cart.php?cmd=export">Export</a><br/> </div> <?php include_once("../templates/template_footer.php");?> </div> </body> </html> 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:- Code: [Select] <?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> 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 Hello everyone,
I have one humble request and I hope someone here will help me.
Before I start, I have to say that I'm clueless about PHP and I'm in a little rush, so that's why I don't have a lot time to learn about PHP.
My problem is:
- I have a IBM DB2 table on one side, and PHP application on other. DB2 table is like a "temporary" table.
- All data from table has to be inserted into PHP application, which should then send those data to another tables back in DB2, with same types.
I'm trying to automatically insert some values made in MS Excel solution via DB2. Values should be inserted into PHP application and saved, so that user can see those entries done. I'm just trying to eliminate double entering of same data from MS Excel. I believe when values are inserted and saved, all datas will be automatically send to another tables - because application allready does that.
Table data is: _Date_,_Name_,_Start_Time,_End_Time_ (and PHP application has input fields for that)
What I need is just some links to what kind of PHP coding I should use, or maybe even better If someone provides me a simple example. Code should prefferable be generated from a cmd_button in PHP application.
I'm sorry in advance If question is stupid, probably only some export command should be done, but I still need an example of PHP code for that.
I hope I was clear!
Thanks for help !!
Edited by Lukael, 14 October 2014 - 03:15 AM. I am trying to export a dynamically created table (one that has been filtered from user inputs) into a csv file format. I have simplified the database and code for ease of use. I also have generated the export file which will extract all information from the table in the database, but I need the information that is filtered by the user to be extracted. Files are shown below. How might I modify my export.php file (or other files) to accomplish this? Thanks in Advance export.php <?php include 'config.php'; $table = 'user'; $file = 'export'; $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"); print $csv_output; exit; ?> config.php <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); ?> index.php <?php include('config.php'); //Include the database connections in it's own file, for easy integration in multiple pages. $lastname_result = mysql_query("SELECT lastname FROM user GROUP BY lastname"); $result = mysql_query("SELECT * FROM user"); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="start/jquery-ui-1.8.4.custom.css" rel="stylesheet" type="text/css"/></link> <link href="../themes/style.css" rel="stylesheet" type="text/css" media="print, projection, screen" /></link> <link href="../common.css" rel="stylesheet" type="text/css"></link> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="jquery.tablesorter.js"></script> <script type="text/javascript" src="jquery-ui-1.8.4.custom.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#myTable").tablesorter({widgets: ['zebra']}); $("#options").tablesorter({sortList: [[0,0]], headers: { 3:{sorter: false}, 4:{sorter: false}}}); } ); function reSort(par) { $("#tableBody").empty(); var vfrom = document.getElementById('from').value; var vto = document.getElementById('to').value; $.get('table.list.php?from='+vfrom+'&to='+vto+'&lastname='+par,function(html) { // append the "ajax'd" data to the table body $("#tableBody").append(html); // let the plugin know that we made a update $("#myTable").trigger("update"); // set sorting column and direction, this will sort on the first and third column var sorting = [[0,0]]; // sort on the first column $("#myTable").trigger("sorton",[sorting]); }); } function getNames() { var vfrom = document.getElementById('from').value; var vto = document.getElementById('to').value; $("#selectbox").empty(); $.get('select.list.php?from='+vfrom+'&to='+vto,function(html) { $("#selectbox").append(html); }); } </script> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="5" class="main"> <tr> <td width="160" valign="top"></td> <td width="732" valign="top"> <table width="90%" border="0" align="center"> <form method="post"> <label for="from">From</label> <input type="text" id="from" name="from" onkeyup="getNames();"/> <label for="to">to</label> <input type="text" id="to" name="to" onkeyup="getNames();"/> <select id="selectbox" name="area" onchange="reSort(this.value);"> <option value="">Select an lastname</option> <option value=""></option> <?php while(list($lastname)=mysql_fetch_array($lastname_result)) { echo "<option value='$lastname'>$lastname</option>"; } ?> </select> </form> <form action="export.php"> <input type="Submit" value="Export to Excel"></input> </form> </table> <table id="myTable" class="tablesorter" border="0" cellpadding="5" cellspacing="1"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Birthday</th> <th>Hometown</th> <th>Job</th> </tr> </thead> <tbody id="tableBody"> <?php //added id to the tbody so we could change the content via javascript ?> </tbody> </table> <p> </p> <p> </p> <p align="right"> </p> </td> <td width="196" valign="top"> </td> </tr> </table> </body> </html> select.list.php <?php include('config.php'); //database connections. if(!isset($_GET['to']) && !isset($_GET['from'])) { //if the uri parameters are not there send em to google. header('Location: http://google.com'); exit(); } $from = (isset($_GET['from'])) ? date('Y-m-d',strtotime($_GET['from'])) : NULL; $to = (isset($_GET['to'])) ? date('Y-m-d',strtotime($_GET['to'])) : NULL; if($from != NULL && $to != NULL) { $where = " WHERE birthdate BETWEEN '$from' AND '$to'"; } elseif($from != NULL) { $where = " WHERE birthdate >= '$from'"; } elseif($to != NULL) { $where = " WHERE birthdate <= '$to'"; } $query = "SELECT lastname FROM user $where GROUP BY lastname"; //write the query. //echo $query; $lastname_result = mysql_query($query) or die($query . ' ' . mysql_error()); //execute the query, or die trying. echo '<option value="">Select an lastname</option> <option value=""></option> '; while(list($lastname)=mysql_fetch_array($lastname_result)) { echo "<option value='$lastname'>$lastname</option>"; } ?> table.list.php <?php include('config.php'); //database connection. if(!isset($_GET['lastname'])) { //if the proper get parameter is not there, redirect to google. header('Location: http://google.com'); exit(); } $lastname = preg_replace('~[^A-Za-z]+~','',$_GET['lastname']); //strip out anything but alpha for the name. $lastname = trim($lastname); //trim the name from all whitespace. if($lastname != '') { //check against an empty string. could have just used "empty()". $where = ' WHERE lastname = \'' . $lastname . '\''; //write the where clause. } else { //if lastname is empty, the where clause will be to, and it will return all names. $where = NULL; unset($lastname); } $from = (isset($_GET['from'])) ? date('Y-m-d',strtotime($_GET['from'])) : NULL; $to = (isset($_GET['to'])) ? date('Y-m-d',strtotime($_GET['to'])) : NULL; if($from != NULL && $to != NULL) { $where .= (isset($lastname)) ? ' AND ' : ' WHERE '; $where .= " birthdate BETWEEN '$from' AND '$to'"; } elseif($from != NULL) { $where .= (isset($lastname)) ? ' AND ' : ' WHERE '; $where .= " birthdate >= '$from'"; } elseif($to != NULL) { $where .= (isset($lastname)) ? ' AND ' : ' WHERE '; $where .= " birthdate <= '$to'"; } $query = "SELECT * FROM user $where"; $result = mysql_query($query); //get the database result. while($row=mysql_fetch_assoc($result)){ //loop and display data. ?> <tr> <td><?php echo $row['firstname']; ?></td> <td><?php echo $row['lastname']; ?></td> <td><?php echo $row['age']; ?></td> <td><?php echo $row['birthdate']; ?></td> <td><?php echo $row['hometown']; ?></td> <td><?php echo $row['job']; ?></td> </tr> <?php } // End while loop. ?> sql code Code: [Select] create table `user` ( `id` double , `firstname` varchar (60), `lastname` varchar (24), `age` double , `hometown` varchar (75), `job` varchar (75), `birthdate` date ); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('1','Peter','Griffin','41','Quahog','Brewery','1960-01-01'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('2','Lois','Griffin','40','Newport','Piano Teacher','1961-08-11'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('3','Joseph','Swanson','39','Quahog','Police Officer','1962-07-23'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('4','Glenn','Quagmire','41','Quahog','Pilot','1960-02-28'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('5','Megan','Griffin','16','Quahog','Student','1984-04-24'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('6','Stewie','Griffin','2','Quahog','Dictator','2008-03-03'); I need to write a cron job that will sync 2 databases. Is there a quick way to write an export from one database for import into another? Or do i manually have to write the select statements per table, format them as insert ignore strings, then execute them on the other database? Thanks guys! Hi, I have tried these PDF generators: 1. TCPDF- doesn't support css class. Styles will work if inline. 2. DOMPDF - Supports CSS class. Doesn't have Unicode support. Already tried load_font to convert ttf to amf but still Chinese char are not displayed properly. - Also tried (installed) PDFlib, watermark appears in pdf but characters are not displayed properly. Any suggestion in PDF generator that can do the functionality of TCPDF and DOMPDF? BTW i'm using xampp. Thanks in advance. Dear freak gurus out there, I'm new to php and sql as i learn from online examples . Though there are lots of links and answers out there related to my post but none reflects what i need. You guys my only hope. What i have: 3 tables : each has its own number of fields (tbl1=14 ,tbl2=9,tbl3=9). There is a field in each tables that can be related (FamilyField). What i need: export to csv all the records from all 3 tables which relates to search criteria (by user) based on a field (MembershipField) which the data may vary from other tables. pseudo code: $membership_type =$_POST['mtype']; $sql=" SELECT field1,field2,field5,MembershipField from tbl1, (SELECT field1,field2,MembershipField from tbl2), (SELECT field3,field6,field8,MembershipField from tbl3) WHERE MembershipFied=$membership_type"; export to csv file by using INTO OUTFILE; I have tried all the code i can find to export from 1 table to csv, and i manage to use UNION to get output from 3 tables but unable to export as the error message was "incorrect usage of UNION and INTO. is this possible? or any workaround? guides with samples will be a great help. I created this php class which recieves an sql query from flash and then produces a csv file for download. The code in its current form produces a csv file on the server. However, I want it to save on the client computer with a 'Save As' dialog box. I am testing on localhost. Here is the class: <?php class CSVExport { public function __construct() { require_once 'Zend/Date.php'; require_once 'DatabaseConnection.php'; } public function exportCSV($query) { $result = mysql_query($query); $fname = 'CSVFile.csv'; $headers = array(); $rowArray = array(); $numFields = mysql_num_fields($result); for ($i = 0; $i < $numFields; $i++) { $headers[] = mysql_field_name($result , $i); } $fp = fopen($fname, 'w'); if ($fp && $result) { header('Content-Type: application/csv'); header('Content-Disposition: inline; filename='.$fname); fputcsv($fp, $headers); while ($thisrow = mysql_fetch_row($result)) { fputcsv($fp, $thisrow); } readfile($fname); fclose($fp); } die; } } Thanks ok, so I am not good with arrays, they confuse me. how can I set this up so that $data is all results that are returned from the database that correspond to it? Code: [Select] $data = array( array("firstname" => '$firstname', "lastname" => '$lastname', "age" => '$age')); the original code looked like: Code: [Select] <?PHP $data = array( array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25), array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18), array("firstname" => "James", "lastname" => "Brown", "age" => 31), array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7), array("firstname" => "Michael", "lastname" => "Davis", "age" => 43), array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24), array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27) ); ?> but that won't do it for me. I need it so that the results from the database will automatically be filled in. basically, everyone that is in the database, so when a new member is added, they will show up too. please help I have a table in my php Mysql which contains some values.. Is it possible to get those values then export them to MS word with formatting? and make it like a table? Help pls. Hi I have a page displaying orders from a mysql table. How can i add a button which exports this to an excel file? Is it possible to export a single value from a mysql DB into a pre-existing excel spread sheet? I know how to create a spread sheet from php and mysql, but not a single value into a pre-existing excel document cell. here's basically what I'm doing: Creating a financial expense tracking report in php, user will input each expense, it will keep a running tally of the available funds in user's bank account. The user has an excel spread sheet that requires the current value of available funds and updates a budget forecast according. SO, I need to somehow get the available balance of the bank account (generated by user input) into the pre-existing excel spreadsheet. Any thoughts? I'm totally at a loss. Thanks! Hi: I think this would pertain to a PHP coding feature. I want to give a user the ability to click a link in the admin area called "Export Database" the will export the entire database like: myDataBase.sql and allow them to save it to their computer. They want to be able to make backups without logging into a PHP admin area. I use to do this with Access, but have not done this with mySQL. Has anyone done this before? I have this code that is supposed to export the results of this query into a CSV. When I run the code in Firefox, it works perfectly. The only browser that it doesn't work in is IE. It opens an HTML page with the results on the page instead of prompting to download the CSV. Can anyone help me out? Code: [Select] <?php //code to export report to excel if(isset($_GET['date'])){ include('../inc/db.php'); if (!$link = mysql_connect($dbhost, $dbuser, $dbpass)) { echo 'Could not connect to mysql'; exit; } if (!mysql_select_db($dbname, $link)) { echo 'Could not select database'; exit; } $date = $_GET['date']; $select = "SELECT patients.lname, patients.fname, patients.dob, patients.sex, visit_data.cc, FROM_UNIXTIME(visit_data.reg_time), FROM_UNIXTIME(visit_data.discharged_time), visit_data.disposition, visit_data.leftby FROM patients, visit_data WHERE discharge_date = '$date' AND patients.patientid = visit_data.patientid"; $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) ); $fields = mysql_num_fields ( $export ); for ( $i = 0; $i < $fields; $i++ ) { $header .= mysql_field_name( $export , $i ) . "\t"; } while( $row = mysql_fetch_row( $export ) ) { $line = ''; foreach( $row as $value ) { if ( ( !isset( $value ) ) || ( $value == "" ) ) { $value = "\t"; } else { $value = str_replace( '"' , '""' , $value ); $value = '"' . $value . '"' . "\t"; } $line .= $value; } $data .= trim( $line ) . "\n"; } $data = str_replace( "\r" , "" , $data ); if ( $data == "" ) { $data = "\n(0) Records Found!\n"; } header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=DailyLog.xls"); header("Pragma: no-cache"); header("Expires: 0"); print "$header\n$data"; } ?> Hello, How can I export mysql database (tables) with php from browser to backup.sql , something like in phpMyAdmin. And simple option with file save as??? Thanks Regards Hi, I have a PHP web page that displays the results from an SQL query. I was wondering if there was anything out there that would allow my users to click a link and then export the results of that query to a CSV file? Thanks Matt Hi, Am having a total brain melt down on a php/mysql export script. I've a table wp_bp_xprofile_data with this sort of layout: ID field_id user_id value It shows data like so: id | field_id | user_id | value 1 | 1 | 1| John Smith 2 | 2 | 1 |john@smith.com 3 | 3 | 1 |23 arcacia avenue 4 | 1 | 2 |Fred Smith 5 | 2 | 2 |fred@smith.com 6 | 3 | 2 |999 lets be avenue field_id joins to another table wp_bp_xprofile_fields, where it has id name This shows data like so: id | name 1 | Name 2 | Email 3 | Address What I need to do, is export the data to a csv so the CSV will then show: Name | Email | Address John Smith | john@smith.com | 23 arcacia avenue Fred Smith | fred@smith.com | 999 lets be avenue However, mine keeps coming back Name | Email | Address John Smith john@smith.com 23 arcacia avenue Fred Smith fred@smith.com 999 lets be avenue Here's my code: [php] header ("Content-Disposition:\"inline; filename=export.csv"); header ("Content-type: text/csv\""); $query = "SELECT VALUE FROM `wp_bp_xprofile_data` ORDER BY `wp_bp_xprofile_data`.`user_id` ASC"; $result = mysql_query($query) or die("Query failed : " . mysql_error()); echo "email,telephone,county,town,add 2,add 1,company name,name,acc type,date joined,country\r\n"; //header while($row = mysql_fetch_row($result)){ echo "$row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11]\r\n"; //data echo "$row[]\r\n"; //data } [php] Where am I going wrong? TIA |