Export sql server Query Result in Excel file - php

I have code to export mysql query result data into Excel. But Now I use SQL Server.I haven't idea to fetch number of fields name. I find many blogs but they all are display php function of mysql database. I need php function which usefull to get field name and number from SQL Query Result
$header = '';
$result = '';
$exportData = sqlsrv_query($gaSql['link'], $sQuery) or die("$sQuery: " . sqlsrv_errors());
$fields = mysql_num_fields($exportData);
for ($i = 0; $i < $fields; $i++) {
if (in_array(mysql_field_name($exportData, $i), $_POST['optFieldName'])) {
$header .= mysql_field_name($exportData, $i) . "\t";
}
// $header .= mysql_field_name($exportData, $i) . "\t";
}
//
$row = array();
for ($i = 0; $i < mysql_num_rows($exportData); $i++) {
$result_excel = mysql_fetch_array($exportData);
array_push($row, $result_excel);
}
foreach ($row as $rowvalue) {
$line = '';
for ($j = 0; $j < count($_POST['optFieldName']); $j++) {
$value = $rowvalue[$_POST['optFieldName'][$j]];
if ((!isset($value) ) || ( $value == "" )) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$result .= trim($line) . "\n";
}
$result = str_replace("\r", "", $result);
if ($result == "") {
$result = "\nNo Record(s) Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$result";

Related

Save file on specific directory inside server instead of downloading the file

I'm trying to change this below script that will works and save same file but inside server internal location instead of like it is doing now save file and then upload to my destination.
<?php
session_start();
include("includes/config.inc2.php");
#ini_set('display_errors','Off');
$quantity_store_query = ''; $quantity_store_query1 = '';
if(isset($_REQUEST['store_id']) && $_REQUEST['store_id'] != '')
{
$get_t = mysql_fetch_array(mysql_query("select quantity_store_id from tbl_website where `store_id` = '".$_REQUEST['store_id']."'"));
$quantity_store_query = " pq.quantity_store_id = '".$get_t['quantity_store_id']."' and ";
$quantity_store_query1 = " quantity_store_id = '".$get_t['quantity_store_id']."' and ";
$get_cur = mysql_fetch_array(mysql_query("SELECT currencies_id FROM currencies WHERE code = (SELECT currency FROM tbl_store WHERE store_id = {$_REQUEST['store_id']})"));
$currency = $get_cur['currencies_id'];
}
if(isset($_REQUEST['lowstock']) && $_REQUEST['lowstock'] != '')
{
define("MINI_ITMS_STOCK",5);
$data='';
$csv_output="";
$refundquery = mysql_query("select p.product_name,p.product_code,p.product_desc,p.weight,p.was_price,p.quantity,p.id,p.created_dt from product as p,product_quantity as pq where ".$quantity_store_query." p.id = pq.product_id and pq.`quantity` <= '".MINI_ITMS_STOCK."' group by pq.product_id order by p.created_dt") or die(mysql_error());
if(mysql_num_rows($refundquery) > 0)
{
$row1 = array("Item Name", "Item Code", "Description", "Weight", "Colour", "Size", "Wholesale Price", "Image1", "Image2", "Image3", "Image4", "Image5", "Quantity");
foreach ($row1 as $value1 )
{
$data .= $value1."\t";
}
$data .= "\n";
for($p=0;$p<mysql_num_rows($refundquery);$p++)
{
$orderinfo = mysql_fetch_array($refundquery);
$prod_id = $orderinfo['id'];
$product_name = stripslashes($orderinfo['product_name']);
$product_code = stripslashes($orderinfo['product_code']);
$product_desc = strip_tags(stripslashes($orderinfo['product_desc']));
$weight = stripslashes($orderinfo['weight']);
$was_price = get_table_data("product_price","price","product_id=".$prod_id." AND store_id=".$_REQUEST['store_id'] . " AND currencies_id = $currency");
$colour_name = 'N/A';
$size_name = 'N/A';
$quantity = $info['quantity'];
$barcode = $info['barcode'];
$psql = mysql_query("SELECT * FROM `product_quantity` where ".$quantity_store_query1." product_id = '$prod_id' and `quantity` <= '".MINI_ITMS_STOCK."' LIMIT 12") or die(mysql_error());
if(mysql_num_rows($psql) > 0)
{
for($k=0;$k<mysql_num_rows($psql);$k++)
{
$kinfo = mysql_fetch_array($psql);
$colour_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['color_id']);
$size_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['size_id']);
$images = get_image_data($prod_id,$kinfo['color_id']);
$quantity = $kinfo['quantity'];
$barcode = $kinfo['barcode'];
if($quantity <= MINI_ITMS_STOCK)
{
$export=array($product_name,$product_code,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}
$csv_output .= "\n";
}
}
}
else
{
$p_sql = mysql_query("SELECT * FROM `product` where id = $prod_id and quantity <= ".MINI_ITMS_STOCK." and is_color = 0 and is_size = 0");
if(mysql_num_rows($p_sql) > 0)
{
$kinfo = mysql_fetch_array($p_sql);
$images = get_image_data($prod_id,0);
$export=array($product_name,$product_code,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}$csv_output .= "\n";
}
}
}
$data = str_replace("\r","",$data);
$to_date = date("d-m-y-h-i-s");
$excel_name = "Low_stock_".$to_date;
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"".$excel_name.".xls\"");
header("Pragma: no-cache");
header("Expires: 0");
print $data.$csv_output;
exit;
}
}
if(isset($_REQUEST['outofstock']) && $_REQUEST['outofstock'] != '')
{
define("MINI_ITMS_STOCK",0);
$data='';
$csv_output="";
$refundquery = mysql_query("select p.product_name,p.product_code,p.product_desc,p.weight,p.was_price,p.quantity,p.id,p.created_dt from product as p,product_quantity as pq where ".$quantity_store_query." p.id = pq.product_id and pq.`quantity` <= '".MINI_ITMS_STOCK."' group by pq.product_id order by p.created_dt") or die(mysql_error());
if(mysql_num_rows($refundquery) > 0)
{
$row1 = array("Item Name", "Item Code", "Barcode", "Description", "Weight", "Colour", "Size", "Wholesale Price", "Image1", "Image2", "Image3", "Image4", "Image5", "Quantity");
foreach ($row1 as $value1 )
{
$data .= $value1."\t";
}
$data .= "\n";
for($p=0;$p<mysql_num_rows($refundquery);$p++)
{
$orderinfo = mysql_fetch_array($refundquery);
$prod_id = $orderinfo['id'];
$product_name = stripslashes($orderinfo['product_name']);
$product_code = stripslashes($orderinfo['product_code']);
$product_desc = strip_tags(stripslashes($orderinfo['product_desc']));
$weight = stripslashes($orderinfo['weight']);
$was_price = get_table_data("product_price","price","product_id=".$prod_id." AND store_id=".$_REQUEST['store_id'] . " AND currencies_id = $currency");
$colour_name = 'N/A';
$size_name = 'N/A';
$quantity = $info['quantity'];
$barcode = $info['barcode'];
$psql = mysql_query("SELECT * FROM `product_quantity` where ".$quantity_store_query1." product_id = '$prod_id' and `quantity` <= '".MINI_ITMS_STOCK."'") or die(mysql_error());
if(mysql_num_rows($psql) > 0)
{
for($k=0;$k<mysql_num_rows($psql);$k++)
{
$kinfo = mysql_fetch_array($psql);
$colour_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['color_id']);
$size_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['size_id']);
$images = get_image_data($prod_id,$kinfo['color_id']);
$quantity = $kinfo['quantity'];
$barcode = $kinfo['barcode'];
if($quantity <= MINI_ITMS_STOCK)
{
$export=array($product_name,$product_code,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}
$csv_output .= "\n";
}
}
}
else
{
$p_sql = mysql_query("SELECT * FROM `product` where id = $prod_id and quantity <= ".MINI_ITMS_STOCK." and is_color = 0 and is_size = 0");
if(mysql_num_rows($p_sql) > 0)
{
$kinfo = mysql_fetch_array($p_sql);
$images = get_image_data($prod_id,0);
$export=array($product_name,$product_code,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}$csv_output .= "\n";
}
}
}
$data = str_replace("\r","",$data);
$to_date = date("d-m-y-h-i-s");
$excel_name = "Out_Of_stock_".$to_date;
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"".$excel_name.".xls\"");
header("Pragma: no-cache");
header("Expires: 0");
print $data.$csv_output;
exit;
}
}
if(isset($_REQUEST['stock']) && $_REQUEST['stock'] != '')
{
define("MINI_ITMS_STOCK",'-1');
$data='';
$csv_output="";
$refundquery = mysql_query("select p.main_category_name,p.sub_category_name,p.item_collection,p.product_name,p.product_code,p.product_desc,p.weight,p.was_price,p.quantity,p.id,p.created_dt from product as p,product_quantity as pq where ".$quantity_store_query." p.id = pq.product_id and pq.`quantity` >= '".MINI_ITMS_STOCK."' group by pq.product_id order by p.created_dt") or die(mysql_error());
if(mysql_num_rows($refundquery) > 0)
{
$row1 = array("Main Category","Sub Category","Item Collection","Item Name", "Item Code", "Stock Code", "Barcode", "Description", "Weight", "Colour", "Size", "Wholesale Price", "RRP", "Image1", "Image2", "Image3", "Image4", "Image5", "Quantity", "Quantity Code");
foreach ($row1 as $value1 )
{
$data .= $value1."\t";
}
$data .= "\n";
for($p=0;$p<mysql_num_rows($refundquery);$p++)
{
$orderinfo = mysql_fetch_array($refundquery);
$prod_id = $orderinfo['id'];
$product_name = stripslashes($orderinfo['product_name']);
$product_code = stripslashes($orderinfo['product_code']);
$product_desc = strip_tags(stripslashes($orderinfo['product_desc']));
$item_collection = stripslashes($orderinfo['item_collection']);
$main_category_name = stripslashes($orderinfo['main_category_name']);
$sub_category_name = stripslashes($orderinfo['sub_category_name']);
$weight = stripslashes($orderinfo['weight']);
$was_price = get_table_data("product_price","price","product_id=".$prod_id." AND store_id=".$_REQUEST['store_id'] . " AND currencies_id = $currency");
$was_active = get_table_data("product_website","active","product_id=".$prod_id." AND store_id=".$_REQUEST['store_id'] . "");
$colour_name = 'N/A';
$size_name = 'N/A';
$quantity = $info['quantity'];
$barcode = $info['barcode'];
$psql = mysql_query("SELECT * FROM `product_quantity` where ".$quantity_store_query1." product_id = '$prod_id' and `quantity` >= '".MINI_ITMS_STOCK."'") or die(mysql_error());
$psql2 = mysql_query("SELECT * FROM `product_category` where product_id = $prod_id");
if(mysql_num_rows($psql) > 0)
if($was_active == 1)
{
for($k=0;$k<mysql_num_rows($psql);$k++)
{
$kinfo = mysql_fetch_array($psql);
$kinfo2 = mysql_fetch_array($psql2);
$category_name = get_table_data("category","cat_name","cat_id=".$kinfo2['category_id']);
$colour_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['color_id']);
$size_name = get_table_data("attributes_value","attr_value1","attribute_value_id=".$kinfo['size_id']);
$images = get_image_data($prod_id,$kinfo['color_id']);
$quantity = $kinfo['quantity'];
$barcode = $kinfo['barcode'];
$RRP = ceil($was_price * 2.5);
?>
<?php
if ($quantity > 5) {
$quantity_code = 2;
} elseif ($quantity < 5) {
$quantity_code = 1;
} elseif ($quantity = 0){
$quantity_code = 0;
?>
<?php
$export=array($main_category_name,$sub_category_name,$item_collection,$product_name,$product_code,$product_code.$colour_name.$size_name,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$RRP,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity,$quantity_code);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}
$csv_output .= "\n";
}
}
}
else
{
$p_sql = mysql_query("SELECT * FROM `product` where id = $prod_id and quantity >= ".MINI_ITMS_STOCK." and is_color = 0 and is_size = 0");
if(mysql_num_rows($p_sql) > 0)
if($was_active == 1)
{
$kinfo = mysql_fetch_array($p_sql);
$images = get_image_data($prod_id,0);
$export=array($main_category_name,$sub_category_name,$item_collection,$category_name,$product_name,$product_code,$product_code.$colour_name.$size_name,$barcode,$product_desc,$weight,$colour_name,$size_name,$was_price,$RRP,$images[0], $images[1], $images[2], $images[3], $images[4],$quantity,$quantity_code);
for($i=0; $i<count($export); $i++)
{
$line = ''; $value='';
$value=$export[$i];
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
}
else
{
$value = '"' . $value . '"' . "\t";
}
$line .= stripslashes($value);
$csv_output .= trim($line)."\t";
}$csv_output .= "\n";
}
}
}
$data = str_replace("\r","",$data);
$to_date = date("d-m-y-h-i-s");
$excel_name = "BANNED_STOCK_UPDATE";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"".$excel_name.".xls\"");
header("Pragma: no-cache");
header("Expires: 0");
print $data.$csv_output;
exit;
}
}
?>

Exporting data into Excel file using PHP

My problem looks like this at the front side:
After choosing which of my users I want to export:
I'm sending AJAX request containing their database ids to external file named exportUsers.php.
So this is how back end of my problem looks like:
When data arrive to exportUsers.php, I query the database and make array($data) like this, which I want to export into Excel file.
This is how i tried to trigger download:
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
$flag = false;
foreach($data as $row1) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row1)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
echo implode("\t", array_values($row1)) . "\r\n";
}
$filename = "users_data" . date('Ymd') . ".xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=\"$filename\"");
But this is all I see in Network tool of my browser:
But no download was triggered. Please help
Try this
session_start();
include "connection.php";
$sql= mysql_query("select * from table") or die(print "Failed Download :".mysql_error());
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "FileName.xls";
header('Content-type: application/xls');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
//jzend...
exit;
?>

Convert a mysql for loop to mysqli for loop

I found a piece of code on the internet that does exactly what I was looking for. The code is about downloading the mysql data into excel sheet format using PHP mysql.
The problem is that I need to convert mysql to mysqli functions and it doesn't seems to work. The for loop needs to be completely changed. Any suggestions?
$conn = mysqli_connect("localhost","root","","dvarsam2"); //server,username,password,db
mysqli_query($conn,'SET NAMES utf8');
$setCounter = 0;
$setExcelName = "download_excal_file";
$setSql = "SELECT * FROM wp_applications";
$setRec = mysqli_query($conn,$setSql);
$setCounter = mysql_num_fields($setRec);
for ($i = 0; $i < $setCounter; $i++) {
$setMainHeader .= mysql_field_name($setRec, $i)."\t";
}
while($rec = mysql_fetch_row($setRec)) {
$rowLine = '';
foreach($rec as $value) {
if(!isset($value) || $value == "") {
$value = "\t";
} else {
//It escape all the special charactor, quotes from the data.
$value = strip_tags(str_replace('"', '""', $value));
$value = '"' . $value . '"' . "\t";
}
$rowLine .= $value;
}
$setData .= trim($rowLine)."\n";
}
$setData = str_replace("\r", "", $setData);
if ($setData == "") {
$setData = "\nno matching records found\n";
}
$setCounter = mysql_num_fields($setRec);
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";
For MySQLi:
<?php
$conn = mysqli_connect("localhost","root","","dvarsam2"); //server,username,password,db
mysqli_query($conn,'SET NAMES utf8');
$setExcelName = "download_excal_file";
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
$result = mysqli_query( $conn, "SELECT * FROM wp_applications" );
$i = 0;
while( $row = $result->fetch_assoc() )
{
if( $i == 0 )
{
// Print field names
foreach( $row as $key => $value )
{
echo $key."\t";
}
echo "\n";
}
// Print data
foreach( $row as $key => $value )
{
$value = strip_tags(str_replace('"', '""', trim($value)));
echo '"' . str_replace("\r", "", $value ) . '"' . "\t";
}
echo "\n";
$i++;
}
if( $result->num_rows == 0 ) echo "no matching records found\n";
You can also just fix your SELECT statement to format output in Excel format:
SELECT * FROM mytable
INTO OUTFILE '/mytable.csv'
FIELDS ESCAPED BY '""'
TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n';
See here for more. The code you supplied is from the accepted answer, but I prefer this solution.

How to grab 2 columns of data from a Mysql database and convert it to a csv file

Ok, So I am trying to create an e-mail newsletter sign-up for my site, and the file I created to fetch the 2 columns called Name and Email from my database, doesn't just save those 2 columns to a csv like I want it to. Instead it saves the whole table. I am confused as to what I am doing wrong. Any help is appreciated here is the code.
<?php
function exportMysqlToCsv($table,$filename = 'export.csv')
{
$csv_terminated = "\n";
$csv_separator = ",";
$csv_enclosed = '"';
$csv_escaped = "\\";
$sql_query = "select `Name`, `Email` from $table";
// 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");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
exit;
}
?>
Use the following function and pass it fields as an array:
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ( $fields as $field ) {
if ($field === null && $nullToMysqlNull) {
$output[] = 'NULL';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
}
else {
$output[] = $field;
}
}
return implode( $delimiter, $output );
}

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