MYSQL to sqlsrv

2019-08-16 19:35发布

问题:

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

回答1:

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.



回答2:

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.