PHP SQLSRV export to Excel - php

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?

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 xls export from mysql with multiple input and output

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)

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

MYSQL to sqlsrv

Working on converting my mysql php code to sqlsrv, but having issue finding the same functions.
This is the code:
$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_num_rows($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";
}
I am unsure what the field_type and field_name is equlent in sqlsrv, but this didn't work:
for ($i = 0; $i < sqlsrv_num_fields($result); $i++) {
$type = sqlsrv_get_field($result,$i);
echo sqlsrv_get_field($result,$i) . "\t";
if ($type == "real")
{
$reals[] = $i;
}
}
I am an ASP.Net developer with very little knowledge about PHP. May be something like below will be useful to you. Just check once.
$stmt = sqlsrv_prepare( $conn, $sql );
$result=sqlsrv_query($conn, $sql);
$i=0;
foreach( sqlsrv_field_metadata( $stmt ) as $fieldMetadata ) {
echo $fieldMetadata["Name"]+"\t";
if($fieldMetadata["Type"]=="real")//$fieldMetadata["Type"]=== SQL_REAL
{
$reals[] = $i
}
$i++;
}
I have not run it before posting here, please let me know in case it's not working.
sqlsrv_field_metadata() can provide the information you need, see Microsofts documentation
The type should be 7 (SQL_REAL) for real or 6 (SQL_FLOAT) for float.

Categories