CakeFest 2024: The Official CakePHP Conference

sqlsrv_fetch_array

(No version information available, might only be in Git)

sqlsrv_fetch_arrayRetorna uma linha como um array

Descrição

sqlsrv_fetch_array(
    resource $stmt,
    int $fetchType = ?,
    int $row = ?,
    int $offset = ?
): array

Retorna a próxima linha disponível de dados como um array associativo, um array numérico ou ambos (o padrão).

Parâmetros

stmt

Um recurso de declaração retornado por sqlsrv_query ou sqlsrv_prepare.

fetchType

Uma constante predefinida especificando o tipo de array a ser retornado. Valores possíveis são SQLSRV_FETCH_ASSOC, SQLSRV_FETCH_NUMERIC e SQLSRV_FETCH_BOTH (o padrão).

Um tipo de busca de SQLSRV_FETCH_ASSOC não deve ser usado ao consumir um conjunto de resultados com várias colunas do mesmo nome.

row

Especifica a linha a ser acessada em um conjunto de resultados que usa um cursor rolável. Os valores possíveis são SQLSRV_SCROLL_NEXT, SQLSRV_SCROLL_PRIOR, SQLSRV_SCROLL_FIRST, SQLSRV_SCROLL_LAST, SQLSRV_SCROLL_ABSOLUTE e, SQLSRV_SCROLL_RELATIVE (o padrão). Quando este parâmetro é especificado, o fetchType deve ser definido explicitamente.

offset

Especifica a linha a ser acessada se o parâmetro row for definido como SQLSRV_SCROLL_ABSOLUTE ou SQLSRV_SCROLL_RELATIVE. Observe que a primeira linha em um conjunto de resultados tem índice 0.

Valor Retornado

Retorna um array em caso de sucesso, null se não houver mais linhas para retornar, e false se ocorrer um erro.

Exemplos

Exemplo #1 Recuperando um array associativo.

<?php
$serverName
= "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if(
$conn === false ) {
die(
print_r( sqlsrv_errors(), true));
}

$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if(
$stmt === false) {
die(
print_r( sqlsrv_errors(), true) );
}

while(
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo
$row['LastName'].", ".$row['FirstName']."<br />";
}

sqlsrv_free_stmt( $stmt);
?>

Exemplo #2 Recuperando um array numérico.

<?php
$serverName
= "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if(
$conn === false ) {
die(
print_r( sqlsrv_errors(), true));
}

$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if(
$stmt === false) {
die(
print_r( sqlsrv_errors(), true) );
}

while(
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
echo
$row[0].", ".$row[1]."<br />";
}

sqlsrv_free_stmt( $stmt);
?>

Notas

Não especificar o fetchType ou usar explicitamente o SQLSRV_FETCH_TYPE constante nos exemplos acima retornará um array que possui chaves associativas e numéricas.

Se mais de uma coluna for retornada com o mesmo nome, a última coluna terá precedência. Para evitar colisões de nomes de campo, use aliases.

Se uma coluna sem nome for retornada, a chave associativa para o elemento do array será uma string vazia ("").

Veja Também

  • sqlsrv_connect() - Abre uma conexão com um banco de dados Microsoft SQL Server
  • sqlsrv_query() - Prepara e executa uma consulta
  • sqlsrv_errors() - Retorna informações de erro e aviso sobre a última operação SQLSRV executada
  • sqlsrv_fetch() - Torna a próxima linha em um conjunto de resultados disponível para leitura

add a note

User Contributed Notes 3 notes

up
-2
albornozg dot rene at gmail dot com
5 years ago
Example with an iteration ( SQLSRV_SCROLL_ABSOLUTE ).

for ($i=0; $i < sqlsrv_num_rows($stmt); $i++) {

$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC, SQLSRV_SCROLL_ABSOLUTE , $i );
echo "value of column 1: '.trim($row[0]).', value of column 2: '.trim($row[1]);

}
up
-18
dlyasaitov184 at yandex dot ru
6 years ago
When I try to use SQLSRV_FETCH_BOTH for SQL-statement about "select ... from [viewName]" result set contained superfluous fields( duplicates and other fields from joined tables). Other types of fetchType work correctly.
up
-25
Anonymous
9 years ago
Note that while the docs say to avoid SQLSRV_FETCH_ASSOC when dealing with result sets where multiple fields have the same name, there are cases when this is perfectly valid to do.

Consider the following query:

SELECT * FROM a INNER JOIN b ON a.id = b.id

For any row, if you fetch NUMERIC you'll get a field for both a.id and b.id, which probably isn't very useful.

If you fetch ASSOC, you'll get one field for "id", and given that it's always the same in both tables (because your query insists it is so), you're not at risk of losing anything.

If you're generating output based on an unknown number of fields, the ASSOC behavior might be preferred.
To Top