简体   繁体   中英

How can I get row values and not just column names from sqlsrv_fetch_array() in PHP

This is my PHP code,

I want to display the data, but $row2[$i] only contains the 4 column names in the table,

If I try to display anything beyond index 3, I get the following error Warning: Undefined array key 4 in C:\xampp\htdocs\database.php

I'd like to display the 1000 table values below, but they don't seem to be stored in the $row2[] array. What do I need to add in order to display all values from the query?

Thanks,

    /*Test SQL command*/
    $tsql2 = "SELECT TOP (1000) [TABLE_CATALOG]
      ,[TABLE_SCHEMA]
      ,[TABLE_NAME]
      ,[TABLE_TYPE]
    FROM [History].[INFORMATION_SCHEMA].[TABLES]";
  
    $stmt2 = sqlsrv_query( $conn, $tsql2);  
    if( $stmt2 === false )  
    {  
        echo "Error in executing query.</br>";  
        die( print_r( sqlsrv_errors(), true));  
    }  
    
    /* Retrieve and display the results of the query. */  
    $row2 = sqlsrv_fetch_array($stmt2); 
    
    for ($i = 1; $i < 4 ; $i++) {   
        echo "Query Results: ".$row2[$i]."\t";  
    }
    /* Free statement and connection resources. */  
    sqlsrv_free_stmt( $stmt2); 

sqlsrv_fetch_array will only fetch one row at a time, so you need a loop to get all rows

As described in the documentation see https://www.php.net/manual/de/function.sqlsrv-fetch-array.php

while( $row = sqlsrv_fetch_array( $stmt2, SQLSRV_FETCH_NUMERIC) ) {
    for ($i = 1; $i < 4 ; $i++) {   
        echo "Query Results: ".$row2[$i]."\t";  
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM