mysql export into single excell cell different records - php

Hello I am exporting data from mysql table to excel, I am using a popular code circulating over the internet for the excel export. The problem is that inside my SQL query I am going over a few selections from table which results should be put inside the same excel cell.
Basicaly in one excel cell for column name "titulo" and "status" there are variouse results from the table, right now it lists only one result and I would like to put all the results in one cell of excel devided with comma for example.
Here is the code with the SQL dump:
$sql = "SELECT users.*, cursos.titulo, subscriptions.status
FROM users
LEFT OUTER JOIN subscriptions
ON users.userID = subscriptions.user_id
LEFT OUTER JOIN cursos
ON cursos.id = subscriptions.curso_id";
//Optional: print out title to top of Excel or Word file with Timestamp
//for when file was generated:
//set $Use_Titel = 1 to generate title, 0 not to use title
$Use_Title = 0;
//define date for title: EDIT this to create the time-format you need
$now_date = DATE('m-d-Y H:i');
//define title for .doc or .xls file: EDIT this if you want
$title = "Dump For Table $DB_TBLName from Database $DB_DBName on $now_date";
/*
Leave the connection info below as it is:
just edit the above.
(Editing of code past this point recommended only for advanced users.)
*/
//create MySQL connection
$Connect = #MYSQL_CONNECT($DB_Server, $DB_Username, $DB_Password)
or DIE("Couldn't connect to MySQL:<br>" . MYSQL_ERROR() . "<br>" . MYSQL_ERRNO());
//select database
$Db = #MYSQL_SELECT_DB($DB_DBName, $Connect)
or DIE("Couldn't select database:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());
//execute query
$result = #MYSQL_QUERY($sql,$Connect)
or DIE("Couldn't execute query:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());
//if this parameter is included ($w=1), file returned will be in word format ('.doc')
//if parameter is not included, file returned will be in excel format ('.xls')
IF (ISSET($w) && ($w==1))
{
$file_type = "msword";
$file_ending = "doc";
}ELSE {
$file_type = "vnd.ms-excel";
$file_ending = "xls";
}
//header info for browser: determines file type ('.doc' or '.xls')
HEADER("Content-Type: application/$file_type");
HEADER("Content-Disposition: attachment; filename=MDT_DB_$now_date.$file_ending");
HEADER("Pragma: no-cache");
HEADER("Expires: 0");
/* Start of Formatting for Word or Excel */
IF (ISSET($w) && ($w==1)) //check for $w again
{
/* FORMATTING FOR WORD DOCUMENTS ('.doc') */
//create title with timestamp:
IF ($Use_Title == 1)
{
ECHO("$title\n\n");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\n"; //new line character
WHILE($row = MYSQL_FETCH_ROW($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
FOR($j=0; $j<mysql_num_fields($result);$j++)
{
//define field names
$field_name = MYSQL_FIELD_NAME($result,$j);
//will show name of fields
$schema_insert .= "$field_name:\t";
IF(!ISSET($row[$j])) {
$schema_insert .= "NULL".$sep;
}
ELSEIF ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
}
ELSE {
$schema_insert .= "".$sep;
}
}
$schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
$schema_insert .= "\t";
PRINT(TRIM($schema_insert));
//end of each mysql row
//creates line to separate data from each MySQL table row
PRINT "\n----------------------------------------------------\n";
}
}ELSE{
/* FORMATTING FOR EXCEL DOCUMENTS ('.xls') */
//create title with timestamp:
IF ($Use_Title == 1)
{
ECHO("$title\n");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
FOR ($i = 0; $i < MYSQL_NUM_FIELDS($result); $i++)
{
ECHO MYSQL_FIELD_NAME($result,$i) . "\t";
}
PRINT("\n");
//end of printing column names
//start while loop to get data
WHILE($row = MYSQL_FETCH_ROW($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
FOR($j=0; $j<mysql_num_fields($result);$j++)
{
IF(!ISSET($row[$j]))
$schema_insert .= "NULL".$sep;
ELSEIF ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
ELSE
$schema_insert .= "".$sep;
}
$schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
//following fix suggested by Josue (thanks, Josue!)
//this corrects output in excel when table fields contain \n or \r
//these two characters are now replaced with a space
$schema_insert = PREG_REPLACE("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
PRINT(TRIM($schema_insert));
PRINT "\n";
}
}
?>
So right now in php what this is doing is exporting all the data from table users depending how many times user_id is inside the subscription table. I would like the information from the subscription table to be put inside a single excel cell for every user
What I think right now is that maybe the SQL Query is not the correct one because right now it creates new arrays for every match from the subscription table and it list all the infromation from users just with diferent fields titulo and status

This is simple local machine code for generating xls or csv file, modify as per your requirement
SELECT * FROM table INTO OUTFILE 'c:/folder/excel.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n';

Related

Zero is not showing as prefix in excel file

I have a table contains below data.
emp_name emp_id
Test1 0011
Test2 0532
i am downloading the data in a excell using php. below is the code.
<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "usr"; //MySQL Username
$DB_Password = "pass"; //MySQL Password
$DB_DBName = "db_name"; //MySQL Database Name
$DB_TBLName = "table_name"; //MySQL Table Name
$timezone = +6;
$date_time=gmdate("Y_m_d-H-i-s", time() + 3600*($timezone+date("I")));
$filename = "ALL_Report_$date_time"; //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "SELECT name,emp_id from emp_info";
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or
die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" .
mysql_errno());
//select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Couldn't select
database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" .
mysql_error(). "<br>" . mysql_errno());
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = mysql_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Using this script i am getting the data properly but when i am opening it's in excell. the prefix 0 is not showing in excell sheet.
Data is showing in below format.
emp_name emp_id
Test1 11
Test2 532
Please help how i can get the data with prefix 0 zero.
excel has an issue with displaying leading 0's here a trick in excel
Select the cell or range in question.
Right-click the selected cell or range and choose Format Cells from the context menu.
Click the Number tab.
Choose Custom from the Category list.
In the Type field, enter the number of 0s necessary to accommodate the largest value. For instance, if the largest value contains four digits, enter four 0s.

how to reverse date field from databse to xls file when using join

I'm working with php mysql and I'm generating a XLS file from database values, but my problem is that the date field is coming through as 2014-01-05 but I want it to be 05-01-2014 in my XLS file. I'm showing all fields through a join query (so using select *), and that's why I'm unable to separate the date field to convert it into desired format. How can I achieve this?
Here is my SQL query to generate the XLS:
select * from registration
join programme on registration.id=programme.stuid
join family on registration.id = family.stuid
join address on registration.id = address.stuid
join education on registration.id = education.stuid
join extradetail on registration.id=extradetail.stuid
join workexperience on registration.id=workexperience.stuid
join demanddraft on registration.id = demanddraft.stuid
where (DATE(demanddraft.ApporvedDate) >= '".$term1."'
AND DATE(demanddraft.ApporvedDate) <= '".$term2."')
AND demanddraft.ddstatus = 'Approved'
Here is the whole code for generating xls:
<?php
$term1 = Date("Y-m-d",strtotime($_REQUEST['date1']));
$term2 = Date("Y-m-d",strtotime($_REQUEST['date2']));
$term3 = Date("d-m-Y",strtotime($term1));
$term4 = Date("d-m-Y",strtotime($term2));
$mode = $_REQUEST['mode'];
$choice = $_REQUEST['choice'];
if($mode == 'DD'){
select * from registration
join programme on registration.id=programme.stuid
join family on registration.id = family.stuid
join address on registration.id = address.stuid
join education on registration.id = education.stuid
join extradetail on registration.id=extradetail.stuid
join workexperience on registration.id=workexperience.stuid
join demanddraft on registration.id = demanddraft.stuid
where (DATE(demanddraft.ApporvedDate) >= '".$term1."'
AND DATE(demanddraft.ApporvedDate) <= '".$term2."')
AND demanddraft.ddstatus = 'Approved'
}
//Optional: print out title to top of Excel or Word file with Timestamp
//for when file was generated:
//set $Use_Titel = 1 to generate title, 0 not to use title
$Use_Title = 1;
//define date for title: EDIT this to create the time-format you need
$now_date = date('m-d-Y H:i');
//define title for .doc or .xls file: EDIT this if you want
$title = "Dump For Table $DB_TBLName from Database $DB_DBName on $now_date";
//$date = date('d-M-Y');
/*
Leave the connection info below as it is:
just edit the above.
(Editing of code past this point recommended only for advanced users.)
*/
//create MySQL connection
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password)
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($DB_DBName, $Connect)
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
//if this parameter is included ($w=1), file returned will be in word format ('.doc')
//if parameter is not included, file returned will be in excel format ('.xls')
if (isset($w) && ($w==1))
{
$file_type = "msword";
$file_ending = "doc";
}else {
$file_type = "vnd.ms-excel";
$file_ending = "xls";
}
//header info for browser: determines file type ('.doc' or '.xls')
header("Content-Type: application/$file_type");
//header("Content-Disposition: attachment; filename=$DB_TBLName.$date.$file_ending");
header("Content-Disposition: attachment; filename=$DB_TBLName.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");
/* Start of Formatting for Word or Excel */
if (isset($w) && ($w==1)) //check for $w again
{
/* FORMATTING FOR WORD DOCUMENTS ('.doc') */
//create title with timestamp:
if ($Use_Title == 1)
{
echo("$titlenn");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\r"; //new line character
while($row = mysql_fetch_row($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
//define field names
$field_name = mysql_field_name($result,$j);
//will show name of fields
$schema_insert .= "$field_name:t";
if(!isset($row[$j])) {
$schema_insert .= "NULL".$sep;
}
elseif ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
}
else {
$schema_insert .= "".$sep;
}
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert .= "\t\n";
print(trim($schema_insert));
//end of each mysql row
//creates line to separate data from each MySQL table row
print "n----------------------------------------------------n";
}
}else{
/* FORMATTING FOR EXCEL DOCUMENTS ('.xls') */
//create title with timestamp:
if ($Use_Title == 1)
{
echo("$titlen");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++)
{
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = mysql_fetch_row($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
//$schema_insert = str_replace($sep."$", "", $schema_insert);
//following fix suggested by Josue (thanks, Josue!)
//this corrects output in excel when table fields contain n or r
//these two characters are now replaced with a space
//$schema_insert = preg_replace('\n', ' ', $schema_insert);
//$schema_insert = preg_replace("/n/", "", $schema_insert);
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
}
?>
You just need to reformat the field that contains the date in question, I am assuming its called DateFieldName in my example.
Where you are processing through the result set from your query do something like this ...
//start while loop to get data
while($row = mysql_fetch_row($result))
{
list($y,$m,$d) = explode( '-', $row['DateFieldName'] );
$row['DateFieldName'] = sprintf( '%s-%s-%s', $d, $m, $y );

How to output mysqli_fetch_field_direct?

I'm trying to convert this code from mysql to mysqli. But when I print it and open in excel file I got an error.
Catchable fatal error: Object of class stdClass could not be converted to string in C:\xampplite\htdocs\app\text2.php on line 139
Can someone Teach me how to convert this code in mysqli correctly?
<?PHP
//EDIT YOUR MySQL Connection Info:
$DB_Server = "localhost"; //your MySQL Server
$DB_Username = "root"; //your MySQL User Name
$DB_Password = ""; //your MySQL Password
$DB_DBName = "app"; //your MySQL Database Name
$DB_TBLName = "purchase_order"; //your MySQL Table Name
$mysqli = new mysqli("localhost", "root", "", "app");
//$DB_TBLName, $DB_DBName, may also be commented out & passed to the browser
//as parameters in a query string, so that this code may be easily reused for
//any MySQL table or any MySQL database on your server
if (isset($_POST['supp'])) {
$var = $_POST['supp'];
//DEFINE SQL QUERY:
//edit this to suit your needs
$result = $mysqli->query("Select id, counter, supplier, quantity, unit_cost, SUM(quantity*unit_cost) total_amount from $DB_TBLName where supplier='$var' GROUP BY id");
}
//Optional: print out title to top of Excel or Word file with Timestamp
//for when file was generated:
//set $Use_Titel = 1 to generate title, 0 not to use title
$Use_Title = 1;
//define date for title: EDIT this to create the time-format you need
$now_date = DATE('m-d-Y H:i');
//define title for .doc or .xls file: EDIT this if you want
$title = "Dump For Table $DB_TBLName from Database $DB_DBName on $now_date";
/*
Leave the connection info below as it is:
just edit the above.
(Editing of code past this point recommended only for advanced users.)
*/
//create MySQL connection
//execute query
//if this parameter is included ($w=1), file returned will be in word format ('.doc')
//if parameter is not included, file returned will be in excel format ('.xls')
IF (ISSET($w) && ($w==1))
{
$file_type = "msword";
$file_ending = "doc";
}ELSE{
$file_type = "vnd.ms-excel";
$file_ending = "xls";
}
//header info for browser: determines file type ('.doc' or '.xls')
HEADER("Content-Type: application/$file_type");
HEADER("Content-Disposition: attachment; filename=MDT_DB_$now_date.$file_ending");
HEADER("Pragma: no-cache");
HEADER("Expires: 0");
/* Start of Formatting for Word or Excel */
IF (ISSET($w) && ($w==1)) //check for $w again
{
/* FORMATTING FOR WORD DOCUMENTS ('.doc') */
//create title with timestamp:
IF ($Use_Title == 1)
{
//ECHO("$title\n\n");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\n"; //new line character
while($row = $result->mysqli_fetch_row())
{
//set_time_limit(60); // HaRa
$schema_insert = "";
FOR($j=0; $j<mysqli_num_fields($result);$j++)
{
//define field names
$field_name = mysqli_fetch_field_direct($result,$j);
//will show name of fields
$schema_insert .= "$field_name:\t";
IF(!ISSET($row[$j])) {
$schema_insert .= "NULL".$sep;
}
ELSEIF ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
}
ELSE {
$schema_insert .= "".$sep;
}
}
$schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
$schema_insert .= "\t";
PRINT(TRIM($schema_insert));
//end of each mysql row
//creates line to separate data from each MySQL table row
PRINT "\n----------------------------------------------------\n";
}
}ELSE{
/* FORMATTING FOR EXCEL DOCUMENTS ('.xls') */
//create title with timestamp:
IF ($Use_Title == 1)
{
//ECHO("$title");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
FOR ($i = 0; $i < mysqli_num_fields($result); $i++)
{
ECHO mysqli_fetch_field_direct($result,$i) . "\t";
}
PRINT("\n");
//end of printing column names
//start while loop to get data
while($row = $result->mysqli_fetch_row())
{
//set_time_limit(60); // HaRa
$schema_insert = "";
FOR($j=0; $j<mysqli_num_fields($result);$j++)
{
IF(!ISSET($row[$j]))
$schema_insert .= "NULL".$sep;
ELSEIF ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
ELSE
$schema_insert .= "".$sep;
}
$schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
//following fix suggested by Josue (thanks, Josue!)
//this corrects output in excel when table fields contain \n or \r
//these two characters are now replaced with a space
$schema_insert = PREG_REPLACE("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
PRINT(TRIM($schema_insert));
PRINT "\n";
}
}
?>
And this the error line
137 FOR ($i = 0; $i < mysqli_num_fields($result); $i++)
138 {
139 ECHO mysqli_fetch_field_direct($result,$i) . "\t";
140 }
You can not echo out the output from mysqli_fetch_field_direct() because it:
Returns an object which contains field definition information from the
specified result set.
instead try something like this (from PHP docs) to get a sense of what the returned object contains:
$finfo = mysqli_fetch_field_direct($result,$i);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
Try This
put this code before $mysqli = new mysqli("localhost", "root", "", "app"); line
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED );
You're not using mysqli_fetch_row() correctly.
If you are going to use the object oriented style you need to use
while($row = $result->fetch_row())
However, if you're going to use the procedural style
while($row = mysqli_fetch_row($result))
You just had things a little backward :)
Smack me with some mysqli!!!!

how to print the value instead of id in xls file with php and mysql

I m using PHP Mysql.i submit a form and fetch the data into a table format in my page.now i want that the user can download the xls file from that table but my problem is that in my database table few values are in id form how can i retrieve them in xls file coz in xls file its showing id's as there are id's in databse table.i dont want to submit the values as name coz name can be more than one.
here is my download xls link code:
<span style="float:right;">Download XLS</span>
and here is the customer_xls.php file:
<?php
//EDIT YOUR MySQL Connection Info:
$DB_Server = "localhost"; //your MySQL Server
$DB_Username = "root"; //your MySQL User Name
$DB_Password = ""; //your MySQL Password
$DB_DBName = "xyz"; //your MySQL Database Name
$DB_TBLName = "customers"; //your MySQL Table Name
// $term = $_REQUEST['term'];
//$DB_TBLName, $DB_DBName, may also be commented out & passed to the browser
//as parameters in a query string, so that this code may be easily reused for
//any MySQL table or any MySQL database on your server
//DEFINE SQL QUERY:
//you can use just about ANY kind of select statement you want -
//edit this to suit your needs!
$sql = "Select * from $DB_TBLName";
//die();
//Optional: print out title to top of Excel or Word file with Timestamp
//for when file was generated:
//set $Use_Titel = 1 to generate title, 0 not to use title
$Use_Title = 1;
//define date for title: EDIT this to create the time-format you need
$now_date = date('m-d-Y H:i');
//define title for .doc or .xls file: EDIT this if you want
$title = "Dump For Table $DB_TBLName from Database $DB_DBName on $now_date";
/*
Leave the connection info below as it is:
just edit the above.
(Editing of code past this point recommended only for advanced users.)
*/
//create MySQL connection
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password)
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($DB_DBName, $Connect)
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
//if this parameter is included ($w=1), file returned will be in word format ('.doc')
//if parameter is not included, file returned will be in excel format ('.xls')
if (isset($w) && ($w==1))
{
$file_type = "msword";
$file_ending = "doc";
}else {
$file_type = "vnd.ms-excel";
$file_ending = "xls";
}
//header info for browser: determines file type ('.doc' or '.xls')
header("Content-Type: application/$file_type");
header("Content-Disposition: attachment; filename=$DB_TBLName.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");
/* Start of Formatting for Word or Excel */
if (isset($w) && ($w==1)) //check for $w again
{
/* FORMATTING FOR WORD DOCUMENTS ('.doc') */
//create title with timestamp:
if ($Use_Title == 1)
{
echo("$titlenn");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\r"; //new line character
while($row = mysql_fetch_row($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
//define field names
$field_name = mysql_field_name($result,$j);
//will show name of fields
$schema_insert .= "$field_name:t";
if(!isset($row[$j])) {
$schema_insert .= "NULL".$sep;
}
elseif ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
}
else {
$schema_insert .= "".$sep;
}
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert .= "\t\n";
print(trim($schema_insert));
//end of each mysql row
//creates line to separate data from each MySQL table row
print "n----------------------------------------------------n";
}
}else{
/* FORMATTING FOR EXCEL DOCUMENTS ('.xls') */
//create title with timestamp:
if ($Use_Title == 1)
{
echo("$titlen");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++)
{
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = mysql_fetch_row($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
//$schema_insert = str_replace($sep."$", "", $schema_insert);
//following fix suggested by Josue (thanks, Josue!)
//this corrects output in excel when table fields contain n or r
//these two characters are now replaced with a space
//$schema_insert = preg_replace("/rn|nr|n|r/", " ", $schema_insert);
$schema_insert .= "\n\t";
print(trim($schema_insert));
print "\n\r";
}
}
?>
You have to join your basic table with tables that contains word representation of the id's saved in first table. Example:
Table A:
id | id_user | id_city
1 | 10 | 5
Table B:
id | user_name
10 | Michael
Table C:
id | city_name
5 | New York
For that tables you should build query like this:
SELECT a.id, b.user_name, c.city_name FROM table_a a
JOIN table_b b ON a.id_user = b.id JOIN
JOIN table_c c ON a.id_city = c.id
Result of that query should look like this:
1 | Michael | New York
The other way to get same results is to build subqueries (but this is much more time-consuming than JOIN method). Example:
SELECT id, (SELECT user_name FROM table_b WHERE id = a.id_user) name,
(SELECT city_name FROM table_c WHERE id = a.id_city) city FROM table_a a

Export specific table columns to Excel

I'm trying to export specific column data (i.e., Ticket #, Company/Customer Name, Issue Subject, Date Closed) from my SQL DB table to Excel (.xls), I have the code written but it's exporting my entire Database table. (See code Below)
Specific column data that needs to be exported:
ticketID
name
company
subject
closed
Also is there any way to add a function that only exports a specific range (i.e., Date range from October 1, 2012 to October 31, 2012)?
<?PHP
//EDIT YOUR MySQL Connection Info:
$DB_Server = "localhost"; //your MySQL Server
$DB_Username = "root"; //your MySQL User Name
$DB_Password = ""; //your MySQL Password
$DB_DBName = "my_databse"; //your MySQL Database Name
$DB_TBLName = "my_table"; //your MySQL Table Name
//$DB_TBLName, $DB_DBName, may also be commented out & passed to the browser
//as parameters in a query string, so that this code may be easily reused for
//any MySQL table or any MySQL database on your server
//DEFINE SQL QUERY:
//edit this to suit your needs
$sql = "Select * from $DB_TBLName";
//Optional: print out title to top of Excel or Word file with Timestamp
//for when file was generated:
//set $Use_Titel = 1 to generate title, 0 not to use title
$Use_Title = 1;
//define date for title: EDIT this to create the time-format you need
$now_date = DATE('m-d-Y H:i');
//define title for .doc or .xls file: EDIT this if you want
$title = "Dump For Table $DB_TBLName from Database $DB_DBName on $now_date";
/*
Leave the connection info below as it is:
just edit the above.
(Editing of code past this point recommended only for advanced users.)
*/
//create MySQL connection
$Connect = #MYSQL_CONNECT($DB_Server, $DB_Username, $DB_Password)
or DIE("Couldn't connect to MySQL:<br>" . MYSQL_ERROR() . "<br>" . MYSQL_ERRNO());
//select database
$Db = #MYSQL_SELECT_DB($DB_DBName, $Connect)
or DIE("Couldn't select database:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());
//execute query
$result = #MYSQL_QUERY($sql,$Connect)
or DIE("Couldn't execute query:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());
//if this parameter is included ($w=1), file returned will be in word format ('.doc')
//if parameter is not included, file returned will be in excel format ('.xls')
IF (ISSET($w) && ($w==1))
{
$file_type = "msword";
$file_ending = "doc";
}ELSE {
$file_type = "vnd.ms-excel";
$file_ending = "xls";
}
//header info for browser: determines file type ('.doc' or '.xls')
HEADER("Content-Type: application/$file_type");
HEADER("Content-Disposition: attachment; filename=MDT_DB_$now_date.$file_ending");
HEADER("Pragma: no-cache");
HEADER("Expires: 0");
/* Start of Formatting for Word or Excel */
IF (ISSET($w) && ($w==1)) //check for $w again
{
/* FORMATTING FOR WORD DOCUMENTS ('.doc') */
//create title with timestamp:
IF ($Use_Title == 1)
{
ECHO("$title\n\n");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\n"; //new line character
WHILE($row = MYSQL_FETCH_ROW($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
FOR($j=0; $j<mysql_num_fields($result);$j++)
{
//define field names
$field_name = MYSQL_FIELD_NAME($result,$j);
//will show name of fields
$schema_insert .= "$field_name:\t";
IF(!ISSET($row[$j])) {
$schema_insert .= "NULL".$sep;
}
ELSEIF ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
}
ELSE {
$schema_insert .= "".$sep;
}
}
$schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
$schema_insert .= "\t";
PRINT(TRIM($schema_insert));
//end of each mysql row
//creates line to separate data from each MySQL table row
PRINT "\n----------------------------------------------------\n";
}
}ELSE{
/* FORMATTING FOR EXCEL DOCUMENTS ('.xls') */
//create title with timestamp:
IF ($Use_Title == 1)
{
ECHO("$title\n");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
FOR ($i = 0; $i < MYSQL_NUM_FIELDS($result); $i++)
{
ECHO MYSQL_FIELD_NAME($result,$i) . "\t";
}
PRINT("\n");
//end of printing column names
//start while loop to get data
WHILE($row = MYSQL_FETCH_ROW($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
FOR($j=0; $j<mysql_num_fields($result);$j++)
{
IF(!ISSET($row[$j]))
$schema_insert .= "NULL".$sep;
ELSEIF ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
ELSE
$schema_insert .= "".$sep;
}
$schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
//following fix suggested by Josue (thanks, Josue!)
//this corrects output in excel when table fields contain \n or \r
//these two characters are now replaced with a space
$schema_insert = PREG_REPLACE("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
PRINT(TRIM($schema_insert));
PRINT "\n";
}
}
?>
Change the SQL:
//DEFINE SQL QUERY:
//edit this to suit your needs
$sql = "Select ticketID, name, company, subject, closed from $DB_TBLName";

Categories