Question

Working on converting my mysql php code to sqlsrv, but having issue how to grap the type and name with sqlsrv_field_metadata.

This is the code: EDIT ( I have pasted the whole code here)

 $sql = "
    SELECT tasks.title as Oppgaver, routines.value as Verdi, DATE_FORMAT(routines.date, '%d/%m/%Y') as Dato, routines.time as Tid, emps.user_name as Ansatt
    FROM routines, task_routine, tasks, emps
    WHERE routines.id = task_routine.routine_id
    AND task_routine.task_id = tasks.id
    AND (tasks.title  Like 'C_%') AND routines.emp_id=emps.id 
    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/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;
    }
}*/

$metaData = sqlsrv_field_metadata($result);

for ($i = 0; $i < $metaData; $i++) {
   $type = $metaData[$i]["Type"];
   echo $metaData[$i]["Name"] . "\t";
   if ($type === SQL_REAL) {
      $reals[] = $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";

} 

MYSQL ( WHICH WORKS)

$sql = "
SELECT measurements.title as Maling, routines.value as Verdi, DATE_FORMAT(routines.date, '%d/%m/%Y') as Dato, routines.time 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 
ORDER BY routines.date, routines.time;

";
$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";
$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";
}

I searched on the docoumentation but didn't found out how: http://msdn.microsoft.com/en-us/library/cc296197.aspx

Was it helpful?

Solution

If you echo sqlsrv_field_metadata($stmt) as json object, you can see how to use that function.

Taken from msdn sqlsrv_field_metadata :

$tsql = "SELECT ReviewerName, Comments FROM Production.ProductReview";
$stmt = sqlsrv_prepare( $conn, $tsql);

echo json_encode(sqlsrv_field_metadata($stmt));

will result a JSON string something like:

// Just example, related with nothing
[{
  "Name":"Id",
  "Type":-5,
  "Size":null,
  "Precision":19,
  "Scale":null,
  "Nullable":0
},
{
  "Name":"Username",
  "Type":-9,"Size":50,
  "Precision":null,
  "Scale":null,
  "Nullable":0
}]

From MSDN again:

  • Name : Name of the column to which the field corresponds.
  • Type : Numeric value that corresponds to a SQL type.
  • Size : Number of characters for fields of character type (char(n), varchar(n), nchar(n), nvarchar(n), XML). Number of bytes for fields of binary type (binary(n), varbinary(n), UDT). NULL for other SQL Server data types.
  • Precision : The precision for types of variable precision (real, numeric, decimal, datetime2, datetimeoffset, and time). NULL for other SQL Server data types.
  • Scale : The scale for types of variable scale (numeric, decimal, datetime2, datetimeoffset, and time). NULL for other SQL Server data types.
  • Nullable : An enumerated value indicating whether the column is nullable (SQLSRV_NULLABLE_YES), the column is not nullable (SQLSRV_NULLABLE_NO), or it is not known if the column is nullable (SQLSRV_NULLABLE_UNKNOWN).

Looking again to the result:

  • First row is a column with name Id ("Name": "Id") with type bigint (SQL_BIGINT (-5)) and cannot be NULL (Nullable: 0)
  • Second row is a columnd with name Username with type nvarchar(50) ("Type": -9 and "Size": 50) and cannot be NULL

So, how to get name and types?

Define an array and give it value of sqlsrv_field_metadata($stmt):

$metaData = sqlsrv_field_metadata($stmt); // $result instead of $stmt in your case

Now you can loop with this array:

for ($i = 0; $i < $metaData; $i++) {
   $type = $metaData[$i]["Type"];
   echo $metaData[$i]["Name"] . "\t";
   if ($type === SQL_REAL) {
      $reals[] = $i;
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top