Main
Index
Search
Posts
Who's
Online
Log
In

Home: Products: CMS Builder:
Save to .csv file

 

 


eduran582
User

Sep 7, 2009, 2:33 PM

Post #1 of 20 (6009 views)
Shortcut
Save to .csv file Can't Post

Dave, et al,

My client wants to have the ability to save the mySQL database data to a MS .csv file format (for import to an Excel worksheet). I found the following script (and reworked it a little) that works fine. It even appends the date and time to the file name (very cool). Problem: I'm not sue how to specify what fields to save (as opposed to all fields). They only want a few of the fields to review. Any suggestions? Unsure

<?
$host = '<your_host>';
$user = '<your_user>';
$pass = '<password>';
$db = '<db_name>';
$table = '<table_name>';
$file = 'output_file_name';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) 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."");
$values = mysql_query("SELECT * FROM $table WHERE paid = '1'");
while ($rowr = mysql_fetch_row($values)) {

for ($j=0;$j<$i-1;$j++) {

$csv_output .=$rowr[$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;
?>

Thanks!

Eric


Chris
Staff


Sep 8, 2009, 6:50 PM

Post #2 of 20 (5986 views)
Shortcut
Re: [eduran582] Save to .csv file [In reply to] Can't Post

Hi Eric,

The script you found doesn't seem to encode special characters (if one of your fields has a comma in it, you're in big trouble!) I think it may also have another bug where it doubles up the last field?

Here's a script I made which uses CMS Builder's getRecords() function instead of doing raw SQL:


Code
<?php 
require_once "C:/wamp/www/cmsbuilder_1_34_build1/cmsAdmin/lib/viewer_functions.php";

// load records
list($records,) = getRecords(array(
'tableName' => 'blog',
'where' => "paid = '1'"
));

// specify fields to output
$fields = array('title', 'category', 'content');

$filename = "blog_".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");

// output csv header row
print(join(',', $fields) . "\n");

// loop over records, outputting a row for each
foreach ($records as $record) {
$row = array();
foreach ($fields as $field) {
$value = $record[$field];
// if this value contains a special character, quote and escape it
if ( preg_match('/[," \t\n]/', $value) ) {
$value = '"' . preg_replace('/"/', '""', $value) . '"';
}
array_push($row, $value);
}
echo(join(',', $row) . "\n");
}

?>


You'd need to replace the parts in red with your own information and you should be good to go! Hope this helps!
Chris


(This post was edited by chris on Sep 9, 2009, 5:50 PM)


eduran582
User

Sep 8, 2009, 8:45 PM

Post #3 of 20 (5983 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Chris,

Thanks for the excellent script! And thanks for pointing out my error in forgetting about 'special characters'. I tried it out and it works great (and quick too)!

Keep up the great work! Wink

Eric


Kenny
User

Sep 9, 2009, 3:23 PM

Post #4 of 20 (5972 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

How would you go about using a search form with this?

My guess is to use the search form to display the results on the page. Then click a link to export those results to csv.

Just not sure how to go about it.


Chris
Staff


Sep 9, 2009, 6:02 PM

Post #5 of 20 (5959 views)
Shortcut
Re: [sagentic] Save to .csv file [In reply to] Can't Post

Hi sagentic,

Since this code is using getRecords() to load the records, any search functionality that works with a regular list viewer page will work with this one.

In fact, you could use one PHP file to produce both your HTML-formatted results and CSV results. The following example would only work with a "get" request, so if your search form has method="post", you'll want to change that.


Code
<?php  
require_once "C:/wamp/www/cmsbuilder_1_34_build1/cmsAdmin/lib/viewer_functions.php";

// load records
list($blogRecords,) = getRecords(array(
'tableName' => 'blog',
'where' => "paid = '1'"
));

// if the user has supplied "as_csv" in query string
if (@$_REQUEST['as_csv']) {

// specify fields to output
$fields = array('title', 'category', 'content');

$filename = "blog_".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");

// output csv header row
print(join(',', $fields) . "\n");

// loop over records, outputting a row for each
foreach ($blogRecords as $record) {
$row = array();
foreach ($fields as $field) {
$value = $record[$field];
// if this value contains a special character, quote and escape it
if ( preg_match('/[," \t\n]/', $value) ) {
$value = '"' . preg_replace('/"/', '""', $value) . '"';
}
array_push($row, $value);
}
echo(join(',', $row) . "\n");
}

// exit -- we are finished with the page
exit;
}

?>

... (a regular list page) ...

<a href="?as_csv=1&<?php echo @$_SERVER['QUERY_STRING'] ?>">Download these results in CSV format</a>

Chris


(This post was edited by chris on Sep 12, 2009, 8:19 AM)


Kenny
User

Sep 11, 2009, 6:12 PM

Post #6 of 20 (5928 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Ok - almost there.

I am getting an error that I'm not sure how to work out:

Notice: Undefined index: as_csv in /home/csoccer/public_html/schedules/local2.php on line 9
Notice: Undefined variable: local_schedulesRecords in /home/csoccer/public_html/schedules/local2.php on line 76 Warning: Invalid argument supplied for foreach() in /home/csoccer/public_html/schedules/local2.php on line 76


I have attached my search file and list page.


Kenny
Attachments: search.php (1.17 KB)
  local2.php (4.08 KB)


Chris
Staff


Sep 12, 2009, 8:27 AM

Post #7 of 20 (5910 views)
Shortcut
Re: [sagentic] Save to .csv file [In reply to] Can't Post

Hi Kenny,

Oops! I fixed my above post to correct the error you got (added the two @ characters.) I also marked off the places where you'll need to customize things in red. You ran into the second bug because we used different names for our record variables. I had originally called mine $records, which was easy to miss. It's now red and called $blogRecords, which you'll want to change to $local_schedulesRecords.

Hope this helps! :D
Chris


(This post was edited by chris on Sep 12, 2009, 8:29 AM)


Kenny
User

Sep 14, 2009, 8:05 PM

Post #8 of 20 (5866 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Forgot to tell you that this worked great! Thanks!

Kenny


northernpenguin
User

Jun 24, 2010, 5:27 AM

Post #9 of 20 (4479 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Chris: This is a very useful code which works really well for what I want to do. Unfortunately, I am having one problem. The way I have it setup, the user runs the search, and the search result is displayed in a separate file (php/html). When I use your code it works, but it sends all the records to the csv, not just the output of the search.

How can I narrow the output to just the output of the search?

Thanx........... Ragi
--
northernpenguin
Northern Penguin Technologies

"Any sufficiently advanced technology
is indistinguishable from magic."
........Arthur C. Clarke


Chris
Staff


Jun 24, 2010, 2:26 PM

Post #10 of 20 (4458 views)
Shortcut
Re: [northernpenguin] Save to .csv file [In reply to] Can't Post

Hi Ragi,

Are you saying that your HTML search result page has a link to download a CSV of the results you're currently looking at -- but that the CSV returns all the records?

If so, you'll need to pass the query forward from your search results page to the CSV request. Try replacing your CSV link with this:


Code
<a href="csv.php?<?php $r = $_REQUEST; unset( $r['page'] ); echo http_build_query($r); ?>"> 
Download a CSV of these results
</a>


If that isn't what's happening, please provide more details on your setup: either a link or attaching your PHP source code would be helpful. :)
Chris


northernpenguin
User

Jun 25, 2010, 3:53 AM

Post #11 of 20 (4445 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Chris: It didn't work. All it did was re-display the exact same search and display it. Looks like it didn't even try to save the output as a csv, so I believe there may be something missing?? Just in case, I have uploaded the two files that generate/display the query.



Thanx........... Ragi
--
northernpenguin
Northern Penguin Technologies

"Any sufficiently advanced technology
is indistinguishable from magic."
........Arthur C. Clarke
Attachments: index.php (5.03 KB)
  specialResults.php (4.12 KB)


Chris
Staff


Jun 28, 2010, 2:41 PM

Post #12 of 20 (4368 views)
Shortcut
Re: [northernpenguin] Save to .csv file [In reply to] Can't Post

Hi Ragi,

Here's the line you have which links to the CSV file:


Code
<center><a href="?as_csv=1&<?php echo @$_SERVER['QUERY_STRING'] ?>">Download these results in CSV format</a></center>


QUERY_STRING won't contain all the form data. I noticed that you solved the problem a few lines below though!

Try changing this:


Code
	<center><a href="?as_csv=1&<?php echo @$_SERVER['QUERY_STRING'] ?>">Download these results in CSV format</a></center> 

<br />

<div class="searchblock">
<table cellpadding="3">
<?php $query="";
foreach($_REQUEST as $key=>$value){
if($key!="orderBy"){
$query.="$key=$value&";
}
}
?>


... to this:


Code
    	<?php $query=""; 
foreach($_REQUEST as $key=>$value){
if($key!="orderBy"){
$query.="$key=$value&";
}
}
?>


<center><a href="?<?php echo $query ?>as_csv=1">Download these results in CSV format</a></center>

<br />

<div class="searchblock">
<table cellpadding="3">


Does that help? Please let us know if you have any questions.
Chris


northernpenguin
User

Jun 29, 2010, 6:12 AM

Post #13 of 20 (4358 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Hi Chris:

Worked great!

Thank you

Ragi
--
northernpenguin
Northern Penguin Technologies

"Any sufficiently advanced technology
is indistinguishable from magic."
........Arthur C. Clarke

(This post was edited by northernpenguin on Jun 29, 2010, 6:14 AM)


northernpenguin
User

Nov 26, 2010, 10:38 AM

Post #14 of 20 (3543 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Jason: I made a small change to my query to limit the number of records displayed on the page to 15. However, when I select the csv output, the csv file only includes the records currently displayed on the page. I want to see the results of the query in the csv file, not just the 1st page.

How can I fix this?
--
northernpenguin
Northern Penguin Technologies

"Any sufficiently advanced technology
is indistinguishable from magic."
........Arthur C. Clarke


Chris
Staff


Nov 26, 2010, 3:02 PM

Post #15 of 20 (3538 views)
Shortcut
Re: [northernpenguin] Save to .csv file [In reply to] Can't Post

Hi Ragi,

I'm guessing you added something like the line in red?


Code
  list($dms_home_pageRecords, $dms_home_pageMetaData) = getRecords(array( 
'tableName' => 'dms_home_page',
'limit' => 15,
));


// if the user has supplied "as_csv" in query string
if (@$_REQUEST['as_csv']) {


Try this:


Code
  $limit = 15; 
if (@$_REQUEST['as_csv']) {
$limit = ''; // no limit for 'as_csv' requests!
}

list($dms_home_pageRecords, $dms_home_pageMetaData) = getRecords(array(
'tableName' => 'dms_home_page',
'limit' => $limit,
));


// if the user has supplied "as_csv" in query string
if (@$_REQUEST['as_csv']) {


Does that help? Please let me know if you have any questions.
Chris


northernpenguin
User

Nov 29, 2010, 4:28 AM

Post #16 of 20 (3519 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Chris: The spreadsheet now contains all records, but the view only prints the top 15 records, no more, no less.

ragi
--
northernpenguin
Northern Penguin Technologies

"Any sufficiently advanced technology
is indistinguishable from magic."
........Arthur C. Clarke

(This post was edited by northernpenguin on Nov 29, 2010, 4:29 AM)


Chris
Staff


Nov 29, 2010, 11:46 AM

Post #17 of 20 (3510 views)
Shortcut
Re: [northernpenguin] Save to .csv file [In reply to] Can't Post

Hi Ragi,

Is that not what you wanted? If not, please explain to me exactly how you want things to work.
Chris


northernpenguin
User

Nov 29, 2010, 11:56 AM

Post #18 of 20 (3507 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Chris: I want the view to display the records 15 at a time, but the spreadsheet to include all the records in the query.

Hope this clears things up.

Thanx.......... Ragi
--
northernpenguin
Northern Penguin Technologies

"Any sufficiently advanced technology
is indistinguishable from magic."
........Arthur C. Clarke


Chris
Staff


Nov 29, 2010, 12:13 PM

Post #19 of 20 (3506 views)
Shortcut
Re: [northernpenguin] Save to .csv file [In reply to] Can't Post

Hi Ragi,

Oh! Is this what you're looking for?


Code
  $perPage = 15;  
if (@$_REQUEST['as_csv']) {
$perPage = ''; // no limit for 'as_csv' requests!
}

list($dms_home_pageRecords, $dms_home_pageMetaData) = getRecords(array(
'tableName' => 'dms_home_page',
'perPage' => $perPage,
));


// if the user has supplied "as_csv" in query string
if (@$_REQUEST['as_csv']) {

Chris


northernpenguin
User

Nov 30, 2010, 4:42 AM

Post #20 of 20 (3495 views)
Shortcut
Re: [chris] Save to .csv file [In reply to] Can't Post

Great! That's exactly waht I was looking for.



Thanx Chris
--
northernpenguin
Northern Penguin Technologies

"Any sufficiently advanced technology
is indistinguishable from magic."
........Arthur C. Clarke