CakeFest 2024: The Official CakePHP Conference

sqlsrv_fetch_array

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

sqlsrv_fetch_arrayDevuelve una fila como un array

Descripción

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

Devuelve la siguiente fila de datos disponible como un array asociativo, un array numérico, o ambos (por defecto).

Parámetros

stmt

Un recurso de sentencia devuelta por sqlsrv_query o sqlsrv_prepare.

fetchType

Una constante predefinida con el tipo de array a devolver. Los valores posibles son SQLSRV_FETCH_ASSOC, SQLSRV_FETCH_NUMERIC, y SQLSRV_FETCH_BOTH (por defecto).

El tipo de objeto devuelto SQLSRV_FETCH_ASSOC no debe utilizarse cuando se trate un conjunto de resultados con múltiples columnas con el mismo nombre.

row

Especifica la fila para acceder a un conjunto de resultados que utiliza un cursor con scroll. Los valores posibles son SQLSRV_SCROLL_NEXT, SQLSRV_SCROLL_PRIOR, SQLSRV_SCROLL_FIRST, SQLSRV_SCROLL_LAST, SQLSRV_SCROLL_ABSOLUTE y, SQLSRV_SCROLL_RELATIVE (por defecto). Cuando se especifica este parámetro, el parámetro fetchType debe ser definido explícitamente.

offset

Especifica la fila a la que se desea acceder si el parámetro de fila se define como SQLSRV_SCROLL_ABSOLUTE o SQLSRV_SCROLL_RELATIVE. Notar que la primera fila en un conjunto de resultado tiene el índice 0.

Valores devueltos

Devuelve un array en caso de éxito, null si no hay más filas a devolver, y false si se produce un error.

Ejemplos

Ejemplo #1 Devolver un array asociativo.

<?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);
?>

Ejemplo #2 Devolver un 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

Cuando no se especifica el parámetro fetchType o se utiliza explícitamente la constante SQLSRV_FETCH_TYPE en los ejemplos anteriores, se devolverá un array que tiene tanto claves asociativas como claves nuéricas.

Si se devuelve más de una columna con el mismo nombre, la última columna tendrá prioridad para tomar el nombre. Para evitar colisiones de nombre de campo, utilizar alias.

Si se devuelve una columna sin nombre, la clave asociativa para ese elemento del array será un string vacío ("").

Ver también

  • sqlsrv_connect() - Abre una conexión a una base de datos Microsoft SQL Server
  • sqlsrv_query() - Prepares and executes a query
  • sqlsrv_errors() - Devuelve información de errores y alertas (warnings) de la última operación SQLSRV realizada
  • sqlsrv_fetch() - Hace que esté disponible para ser leída la siguiente fila del conjunto de resultado

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