PHP School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a PHP Expert!

Join 300,391 PHP Programmers for FREE! Get instant access to thousands of PHP experts, tutorials, code snippets, and more! There are 1,568 people online right now. Registration is fast and FREE... Join Now!




downloading CSV files

 

downloading CSV files

NeekWorld

1 Jul, 2009 - 06:57 PM
Post #1

New D.I.C Head
*

Joined: 5 Oct, 2008
Posts: 49


My Contributions
ok i have a script that is supposed to download the contents of my table in my database. the only problem is i only want to download a specified row from the table does anyone know how to do this.

this is the code i have. it creates and downloads the csv file, inserts the column headers in the file but not the data in the colums.

CODE
$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." WHERE orderID ='$colname_Recordset1'");
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;


it works fine if i dont have the where clause but i dont want the entire contents of the table just where the orderID = the orderID provided.

i get an error that what ever i put in is not declared, but i have given it a session id from page that the link is on shouldnt that still work here? or do i need something else?

User is offlineProfile CardPM
+Quote Post


noorahmad

RE: Downloading CSV Files

1 Jul, 2009 - 08:26 PM
Post #2

Webmaster
Group Icon

Joined: 12 Mar, 2009
Posts: 2,018



Thanked: 125 times
Dream Kudos: 1350
My Contributions
Could Please Past Your Error?
User is online!Profile CardPM
+Quote Post

NeekWorld

RE: Downloading CSV Files

1 Jul, 2009 - 09:01 PM
Post #3

New D.I.C Head
*

Joined: 5 Oct, 2008
Posts: 49


My Contributions
QUOTE(noorahmad @ 1 Jul, 2009 - 08:26 PM) *

Could Please Past Your Error?


this displays in the csv file not on the site
CODE
Notice:  Undefined variable: colname_Recordset1 in C:\wamp\www\Site\csv2.php on line 31


i tried doing with the session variable i set as the info from the text box and the above is with the info from the record set, either way i get the same error message
User is offlineProfile CardPM
+Quote Post

noorahmad

RE: Downloading CSV Files

1 Jul, 2009 - 09:10 PM
Post #4

Webmaster
Group Icon

Joined: 12 Mar, 2009
Posts: 2,018



Thanked: 125 times
Dream Kudos: 1350
My Contributions
QUOTE
$values = mysql_query("SELECT * FROM ".$table." WHERE orderID ='$colname_Recordset1'"


here is you error $colname_Recordset1 where is variable comes from.

User is online!Profile CardPM
+Quote Post

NeekWorld

RE: Downloading CSV Files

1 Jul, 2009 - 09:28 PM
Post #5

New D.I.C Head
*

Joined: 5 Oct, 2008
Posts: 49


My Contributions
QUOTE(noorahmad @ 1 Jul, 2009 - 09:10 PM) *

QUOTE
$values = mysql_query("SELECT * FROM ".$table." WHERE orderID ='$colname_Recordset1'"


here is you error $colname_Recordset1 where is variable comes from.


ok i have a link on the page that says Download CSV file
it links to the csv.php file that executes the script that opens the save as dialog box.
it saves the file but in the csv file it inputs the error message , then inputs the column headers from the database. it however does not input the data associated with the columns.

the variable is on the page with the link and yes it is declared i have tried more than one variable. the one you see was declared by dreamweaver when it created the dynamic table i am using. i have also tried to use one that i declared, that directly references the text box i put on the page for the user to insert the orderID number. but i get the same result both times.
User is offlineProfile CardPM
+Quote Post

RudiVisser

RE: Downloading CSV Files

1 Jul, 2009 - 11:18 PM
Post #6

.. does not guess solutions
Group Icon

Joined: 5 Jun, 2009
Posts: 1,872



Thanked: 137 times
Dream Kudos: 125
Expert In: PHP, MySQL, HTML, CSS, C#

My Contributions
QUOTE(noorahmad @ 1 Jul, 2009 - 09:10 PM) *

QUOTE
$values = mysql_query("SELECT * FROM ".$table." WHERE orderID ='$colname_Recordset1'"


here is you error $colname_Recordset1 where is variable comes from.

???????????!!!!!!!!!!???????????

CODE
$values = mysql_query("SELECT * FROM ".$table." WHERE orderID ='$colname_Recordset1'");

If that's your problem, you said it was coming from a session variable.

Is that the whole csv.php file?? Because if so $colname_Recordset1 is not defined at all.

If it is, like you said, in the session, you need to put $_SESSION['colname_Recordset1'].
User is offlineProfile CardPM
+Quote Post

NeekWorld

RE: Downloading CSV Files

2 Jul, 2009 - 05:03 PM
Post #7

New D.I.C Head
*

Joined: 5 Oct, 2008
Posts: 49


My Contributions
QUOTE(MageUK @ 1 Jul, 2009 - 11:18 PM) *

QUOTE(noorahmad @ 1 Jul, 2009 - 09:10 PM) *

QUOTE
$values = mysql_query("SELECT * FROM ".$table." WHERE orderID ='$colname_Recordset1'"


here is you error $colname_Recordset1 where is variable comes from.

???????????!!!!!!!!!!???????????

CODE
$values = mysql_query("SELECT * FROM ".$table." WHERE orderID ='$colname_Recordset1'");

If that's your problem, you said it was coming from a session variable.

Is that the whole csv.php file?? Because if so $colname_Recordset1 is not defined at all.

If it is, like you said, in the session, you need to put $_SESSION['colname_Recordset1'].


ok ill try and explain it again.
i have one page success.php this page has a link on it that links to the csv.php script.
the csv.php script works excellent as long as i dont put in a WHERE clause.
i want the WHERE clause to pull a variable that is in a text box on the success.php page.
on the success.php page i have declared a session for the variable orderID. i want the csv.php to see this variable how do i do it?
User is offlineProfile CardPM
+Quote Post

NeekWorld

RE: Downloading CSV Files

2 Jul, 2009 - 09:50 PM
Post #8

New D.I.C Head
*

Joined: 5 Oct, 2008
Posts: 49


My Contributions
ok i fixed it myself. if i use a button in the form it submits the post variable to the csv.php script and it inserts only the record that i want in the excel file. yeah!!!!!

code here if anyone else would like to know how to do it.
this code will pop up a dialog box for you to save the file where you want. it has an auto name that uses the date/time stamp to name the file but i guess you could change that to what ever when the dialog box pops up.

this is the code from the main page.
CODE

    <form id="form1" name="form1" method="post" action="mycsv.php">
      <label>Order ID<br />
      <input type="text" name="orderID" id="orderID" />
      </label>
      <input name="Submit" type="submit" />
    </form>
   <?php
        $orderID = $_POST['orderID'];
        $_SESSION['orderID'] = $orderID;
    ?>


mycsv.php file
CODE
<?php

$host = 'insert your host here'; // MYSQL database host adress
$db = 'insert your database here'; // MYSQL database name
$user = 'insert your database user here'; // Mysql Datbase user
$pass = 'insert database password'; // Mysql Datbase password

// Connect to the database
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db);

require 'exportcsv.inc.php';

$table="insert your table here"; // this is the tablename that you want to export to csv from mysql.

exportMysqlToCsv($table);

?>


exportcsv.inc.php file
CODE

<?php

function exportMysqlToCsv($table,$filename = 'export.csv')
{
    $csv_terminated = "\n";
    $csv_separator = ",";
    $csv_enclosed = '"';
    $csv_escaped = "\\";
    $sql_query = "select * from $table WHERE orderID =" .$_POST['orderID']."";

    // Gets the data from the database
    $result = mysql_query($sql_query);
    $fields_cnt = mysql_num_fields($result);


    $schema_insert = '';

    for ($i = 0; $i < $fields_cnt; $i++)
    {
        $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
            stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
        $schema_insert .= $l;
        $schema_insert .= $csv_separator;
    } // end for

    $out = trim(substr($schema_insert, 0, -1));
    $out .= $csv_terminated;

    // Format the data
    while ($row = mysql_fetch_array($result))
    {
        $schema_insert = '';
        for ($j = 0; $j < $fields_cnt; $j++)
        {
            if ($row[$j] == '0' || $row[$j] != '')
            {

                if ($csv_enclosed == '')
                {
                    $schema_insert .= $row[$j];
                } else
                {
                    $schema_insert .= $csv_enclosed .
                    str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
                }
            } else
            {
                $schema_insert .= '';
            }

            if ($j < $fields_cnt - 1)
            {
                $schema_insert .= $csv_separator;
            }
        } // end for

        $out .= $schema_insert;
        $out .= $csv_terminated;
    } // end while

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: " . strlen($out));
    // Output to browser with appropriate mime type, you choose;)
    header("Content-type: text/x-csv");
    //header("Content-type: text/csv");
    //header("Content-type: application/csv");
    $filename = $filename."_".date("Y-m-d_H-i",time());
    header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    header( "Content-disposition: filename=".$filename.".csv");

    //header("Content-Disposition: attachment; filename=$filename");
    echo $out;
    exit;

}

?>


if you want it to export a single row this will work just change the line below to your variable

CODE
    $sql_query = "select * from $table WHERE orderID =" .$_POST['orderID']."";


or if you want it to download the entire contents of the table change it to

CODE
$sql_query = "select * from $table";


This post has been edited by NeekWorld: 2 Jul, 2009 - 09:51 PM
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/7/09 09:47PM

Live PHP Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

PHP Tutorials

Reference Sheets

PHP Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month