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 typebigint
(SQL_BIGINT (-5)) and cannot be NULL (Nullable
: 0) - Second row is a columnd with name
Username
with typenvarchar(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;
}
}