PHP xls export from mysql with multiple input and output - php

I want to export multiple data in to xls. The user can input a id (13,42,192) and the script write xls.
if(isset($_POST['download_xls'])) {
$filename = 'id_'.$id.'_'.$db_tabel.'_'.date('d-m-Y_H-i',time());
$id_suche = explode(",", str_replace(" ", "", $_POST['id_suche']));
header("Content-Type: application/xls; charset=utf-8");
header("Content-Disposition: attachment; filename=".$filename.".xls");
header("Pragma: no-cache");
header("Expires: 0");
print("id\tlayout\tmenge\tname\tvorname\tlieferadresse\tbesteller_name\tbesteller_email\tmitteilung");
print("\n");
foreach ($id_suche as $tmp_id) {
$query = "SELECT id, layout, menge, name, vorname, lieferadresse, besteller_name, besteller_email, mitteilung FROM be_bestellungen WHERE id = ".$tmp_id;
$result = mysql_query($query, $db);
$sep = "\t";
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));
die;
}
}
}
the script write only 1 data in xls. if i write one id in the input field no resulte.
thanks

First of all use the mysli_* class
And the answer to your question:
Remove the die(); in your while loop
If you want to go to the next iteration in the loop use continue;
If you want to break the loop use break;
php.net is your best friend (link)

Related

(PHP) MySQL to Excel export generates a file with different cells format

Although both DATA 1 & DATA 2 are varchar on my MySQL Database, when I export my table that contains DATA 1 & DATA 2 using PHP (see code below) I get an Excel file where DATA 2 cells are in the General format (which is ok) and DATA 1 cells in Number format (which is not ok, I want them to be general too in order to avoid decimal separator).
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t";
$sql="SELECT * FROM $DB_TBLName WHERE `userID`=$id";
$resultt = $con->query($sql);
while ($property = mysqli_fetch_field($resultt)) { //fetch table field
name
echo $property->name."\t";
}
fputcsv("\n");
while($row = mysqli_fetch_row($resultt)) //fetch_table_data
{
$schema_insert = "";
for($j=0; $j< mysqli_num_fields($resultt);$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";
fputcsv(trim($schema_insert));
fputcsv "\n";
}
This is what I get:
(Again: DATA 1 is not correct, DATA 2 is correct)

PHP SQLSRV export to Excel

I am using PHP with SQLSRV in an attempt to export a table to Excel. I used this method with MySQLi with no problem.
Regardless, here is the code I am using to export to Excel:
<?php
include("../include/database.php");
global $ts;
$ts = date('mdY-His');
session_start();
$sql = "SELECT
[BOL_DATE]
,[BOOKING_NUM]
,[BOL_NUM]
,[VOYAGE]
....
FROM DETAIL
WHERE
// bunch of other stuff not necessary to show";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=fulldetails-".$ts.".xls");
header("Pragma: no-cache");
header("Expires: 0");
header("Content-Transfer-Encoding: binary ");
$sep = "\t"; //tabbed character
if($result = $dbc->sqlsrv_query($sql)) // <- error is here
{
while( $finfo = sqlsrv_fetch_array($sql, SQLSRV_FETCH_ASSOC) )
{
printf($finfo->name . $sep);
}
}
print("\n");
while( $finfo = sqlsrv_fetch_array($sql, SQLSRV_FETCH_ASSOC) )
{
$schema_insert = "";
for($j = 0; $j < sqlsrv_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";
}
?>
The error I am getting upon firing this process, the Excel sheet shows this error:
Fatal error: Call to a member function sqlsrv_query() on a non-object in C:\server\htdocs\main\reports\reports.php
Which is pointing to the part above where I labeled "error is here".
On the line above where I pointed the error out, I even changed it to this:
if($result = sqlsrv_query($dbc, $update))
But when the results are exported, the excel sheet is blank.
How can I edit my code to make this work?

PHP Excel remove blank rows at top

I am using PHP to export data from a grid view to an Excel spreadsheet. For some reason, there are blank rows at the top.
As you can see in the image above, the headers begin printing at row 9, and of course the data starts to print afterward, that which I did not show.
My code works and does what I need it to do. I am just trying to figure out why it is printing blank rows at the top.
Here is the code:
<?php
$ts = date('mdY-His');
session_start();
$where = $_SESSION['where']; // this is the parameters passed from another file
$sql = "SELECT * FROM mainTable WHERE " . $where . " ORDER BY CON_STATUS;";
$result = mysql_query($sql) or die("<script language='javascript'>
window.alert('There was no data to send')
window.location.href='../home.php'
</script>");
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=importdetails-".$ts.".xls");
header("Pragma: no-cache");
header("Expires: 0");
header("Content-Transfer-Encoding: binary");
$sep = "\t";
for($i = 0; $i < mysql_num_fields($result); $i++)
{
echo mysql_field_name($result, $i) . "\t";
}
print("\n");
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";
}
?>
As stated, my code works, besides the printing of the blank rows at the top of the spreadsheet. If you see anything in my code that will remove the blank rows, that would be greatly appreciated.
I haven't tested this, but it looks to me like a problem with your line
for($j-0; $j < mysql_num_fields($result); $j++)
Noting that you are not setting $j=0, but subtracting 0 from $j

Php excel in one cell

I am working on creating excel from my SQL server, the problem is that the row is in one cell. I want the output to be on each cell in the same row. That will make it easier to edit and sum data.
This is the query and the output in the sql server:
Output in the Excel file:
Code:
$sql = "
SELECT measurements.title as Tittel, routines.value as Verdi, convert(VARCHAR(10), routines.time, 108) as Tid, pools.name as Basseng, emps.user_name as Ansatt
FROM routines, measure_routine, measurements, pools, emps
WHERE routines.id = measure_routine.routine_id
AND measure_routine.measure_id = measurements.id
AND (measurements.title Like 'T_%') AND measure_routine.pool_id=pools.id AND routines.emp_id=emps.id
AND pools.name = 'Hovedbasseng'
ORDER BY routines.date, routines.time;
";
$result=sqlsrv_query($conn,$sql) or die("Couldn't execute query:<br>" . sqlsrv_error(). "<br>" . sqlsrv_errno());
$file_ending = "xls";
$reals=array();
//header info for browser
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
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
$i=0;
foreach( sqlsrv_field_metadata( $result ) as $fieldMetadata ) {
echo $fieldMetadata["Name"]+"\t";
if($fieldMetadata["Type"]=="real")//$fieldMetadata["Type"]=== SQL_REAL
{
$reals[] = $i;
}
$i++;
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = sqlsrv_fetch_array($result))
{
$schema_insert = "";
for($j = 0; $j < sqlsrv_num_fields($result); $j++)
{
if ($row[$j] != "") {
if (in_array($j, $reals)) {
$schema_insert .= str_replace(".",",", $row[$j]) . $sep;
} else {
$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";
}
?>
Do this:
Open phpMyadmin
Log in
open table you want to grab
click export
choose file type you want to export it as

Excel returning 0

Trying to generate excel file from my sql server, but it's returning 0 in the excel file. Not sure why.
SQLSRV version which returns 0 in the excel document.
$result=sqlsrv_query($conn,$sql) or die("Couldn't execute query:<br>" . sqlsrv_error(). "<br>" . sqlsrv_errno());
$file_ending = "xls";
$reals=array();
//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 < sqlsrv_num_fields($result); $i++) {
$type = sqlsrv_field_metadata($result,$i);
echo sqlsrv_field_metadata($result,$i) . "\t";
if ($type == "real")
{
$reals[] = $i;
}
}
*/
$i=0;
foreach( sqlsrv_field_metadata( $result ) as $fieldMetadata ) {
echo $fieldMetadata["Name"]+"\t";
if($fieldMetadata["Type"]=="real")//$fieldMetadata["Type"]=== SQL_REAL
{
$reals[] = $i;
}
$i++;
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = sqlsrv_fetch($result))
{
$schema_insert = "";
for($j=0; $j<sqlsrv_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != ""){
if (in_array($j, $reals)){
$schema_insert .= str_replace(".",",","$row[$j]").$sep;
} else {
$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";
}
MYSQL version, which works perfectly:
$result = #mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$file_ending = "xls";
$reals=array();
//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++) {
$type = mysql_field_type($result,$i);
echo mysql_field_name($result,$i) . "\t";
if ($type == "real")
{
$reals[] = $i;
}
}
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] != ""){
if (in_array($j, $reals)){
$schema_insert .= str_replace(".",",","$row[$j]").$sep;
} else {
$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";
}
sqlsrv_fetch() makes the next result set available for reading so, if you want to read data as $row[$j], you should use sqlsrv_get_field($result, $j):
while(sqlsrv_fetch($result))
{
$schema_insert = "";
for($j = 0; $j < sqlsrv_num_fields($result); $j++)
{
if (sqlsrv_get_field($result, $j) != "") {
if (in_array($j, $reals)) {
$schema_insert .= str_replace(".",",", sqlsrv_get_field($result, $j)) . $sep;
} else {
$schema_insert .= sqlsrv_get_field($result, $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";
}
Note that I removed if(isset($row[$j])) check as it is unneccessary.
One more way(and less complicated I think for your use) is to use sqlsrv_fetch_array(). If you won't return a field value as a specific type(e.g. string), you can use that function to return result sets as arrays:
while($row = sqlsrv_fetch_array($result))
{
$schema_insert = "";
for($j = 0; $j < sqlsrv_num_fields($result); $j++)
{
if ($row[$j] != "") {
if (in_array($j, $reals)) {
$schema_insert .= str_replace(".",",", $row[$j]) . $sep;
} else {
$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";
}
One more thing to add, I removed also double quotes from around of $row[$j] however I'm not sure so you can add them again.
You should refer more to the documentation. It has very clear examples with very good explanations.
SQLSRV Driver API Reference
SQLSRV Functions

Categories