sqlsrv_query

Scaricare il driver PHP

Prepara ed esegue un'istruzione.

Sintassi

  
sqlsrv_query(resource $conn, string $tsql [, array $params [, array $options]])  

Parametri

$conn: risorsa di connessione associata all'istruzione preparata.

$tsql: espressione Transact-SQL corrispondente all'istruzione preparata.

$params [FACOLTATIVO]: matrice di valori corrispondenti ai parametri di una query con parametri. Ogni elemento della matrice può corrispondere a uno dei seguenti:

  • Valore letterale.

  • Variabile PHP.

  • Matrice con la struttura seguente:

    array($value [, $direction [, $phpType [, $sqlType]]])  
    

    La descrizione di ogni elemento della matrice è visualizzata nella tabella seguente:

    Elemento Descrizione
    $value Un valore letterale, una variabile PHP o una variabile PHP per riferimento.
    $direction[facoltativo] Una delle costanti SQLSRV_PARAM_* seguenti usate per indicare la direzione del parametro: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. Il valore predefinito è SQLSRV_PARAM_IN.

    Per altre informazioni sulle costanti PHP, vedere Costanti (driver Microsoft per PHP per SQL Server).
    $phpType[facoltativo] Costante SQLSRV_PHPTYPE_* che specifica il tipo di dati PHP del valore restituito.

    Per altre informazioni sulle costanti PHP, vedere Costanti (driver Microsoft per PHP per SQL Server).
    $sqlType[facoltativo] Costante SQLSRV_SQLTYPE_* che specifica il tipo di dati SQL Server del valore di input.

    Per altre informazioni sulle costanti PHP, vedere Costanti (driver Microsoft per PHP per SQL Server).

$options [FACOLTATIVO]: matrice associativa che imposta le proprietà delle query. È lo stesso elenco di chiavi supportate anche da sqlsrv_prepare.

Valore restituito

Risorsa di istruzione. Se non è possibile creare e/o eseguire l'istruzione, viene restituito false.

Osservazioni

La funzione sqlsrv_query è particolarmente adatta alle query eseguite una sola volta e deve essere la scelta predefinita per l'esecuzione di query, a meno che non si verifichino circostanze speciali. Questa funzione fornisce un metodo semplificato per eseguire una query con una quantità minima di codice. La funzione sqlsrv_query esegue sia la preparazione che l'esecuzione dell'istruzione e può essere usata per eseguire query con parametri.

Per altre informazioni, vedere Procedura: Recuperare i parametri di output mediante il driver SQLSRV.

Esempio 1

Nell'esempio seguente viene inserita un'unica riga nella tabella Sales.SalesOrderDetail del database AdventureWorks. Nell'esempio si presuppone che SQL Server e il database AdventureWorks siano installati nel computer locale. Quando si esegue l'esempio dalla riga di comando, tutto l'output viene scritto nel browser.

Nota

Nell'esempio seguente viene usata un'istruzione INSERT per illustrare l'uso di sqlsrv_query per l'esecuzione di un'istruzione una sola volta, ma il concetto si applica a qualsiasi istruzione Transact-SQL.

<?php  
/* Connect to the local server using Windows Authentication and  
specify the AdventureWorks database as the database in use. */  
$serverName = "(local)";  
$connectionInfo = array("Database"=>"AdventureWorks");  
$conn = sqlsrv_connect($serverName, $connectionInfo);  
if ($conn === false) {  
    echo "Could not connect.\n";  
    die(print_r(sqlsrv_errors(), true));  
}  
  
/* Set up the parameterized query. */  
$tsql = "INSERT INTO Sales.SalesOrderDetail   
        (SalesOrderID,   
         OrderQty,   
         ProductID,   
         SpecialOfferID,   
         UnitPrice,   
         UnitPriceDiscount)  
        VALUES   
        (?, ?, ?, ?, ?, ?)";  
  
/* Set parameter values. */  
$params = array(75123, 5, 741, 1, 818.70, 0.00);  
  
/* Prepare and execute the query. */  
$stmt = sqlsrv_query($conn, $tsql, $params);  
if ($stmt) {  
    echo "Row successfully inserted.\n";  
} else {  
    echo "Row insertion failed.\n";  
    die(print_r(sqlsrv_errors(), true));  
}  
  
/* Free statement and connection resources. */  
sqlsrv_free_stmt($stmt);  
sqlsrv_close($conn);  
?>  

Esempio 2

L'esempio seguente aggiorna un campo nella tabella Sales.SalesOrderDetail del database AdventureWorks. Nell'esempio si presuppone che SQL Server e il database AdventureWorks siano installati nel computer locale. Quando si esegue l'esempio dalla riga di comando, tutto l'output viene scritto nel browser.

<?php  
/* Connect to the local server using Windows Authentication and  
specify the AdventureWorks database as the database in use. */  
$serverName = "(local)";  
$connectionInfo = array("Database"=>"AdventureWorks");  
$conn = sqlsrv_connect($serverName, $connectionInfo);  
if ($conn === false) {  
    echo "Could not connect.\n";  
    die(print_r(sqlsrv_errors(), true));  
}  
  
/* Set up the parameterized query. */  
$tsql = "UPDATE Sales.SalesOrderDetail   
         SET OrderQty = (?)   
         WHERE SalesOrderDetailID = (?)";  
  
/* Assign literal parameter values. */  
$params = array(5, 10);  
  
/* Execute the query. */  
if (sqlsrv_query($conn, $tsql, $params)) {  
    echo "Statement executed.\n";  
} else {  
    echo "Error in statement execution.\n";  
    die(print_r(sqlsrv_errors(), true));  
}  
  
/* Free connection resources. */  
sqlsrv_close($conn);  
?>  

Nota

È consigliabile usare stringhe come input durante l'associazione di valori a una colonna decimal o numeric per garantire precisione e accuratezza, dato che PHP offre una precisione limitata per i numeri a virgola mobile. Lo stesso vale per le colonne di tipo bigint, soprattutto quando i valori non sono compresi nell'intervallo di un integer.

Esempio 3

Questo esempio di codice mostra come associare un valore decimale come parametro di input.

<?php
$serverName = "(local)";
$connectionInfo = array("Database"=>"YourTestDB");  
$conn = sqlsrv_connect($serverName, $connectionInfo);  
if ($conn === false) {  
     echo "Could not connect.\n";  
     die(print_r(sqlsrv_errors(), true));  
}  

// Assume TestTable exists with a decimal field 
$input = "9223372036854.80000";
$params = array($input);
$stmt = sqlsrv_query($conn, "INSERT INTO TestTable (DecimalCol) VALUES (?)", $params);

sqlsrv_free_stmt($stmt);  
sqlsrv_close($conn);  

?>

Esempio 4

Questo esempio illustra come creare una tabella di tipi sql_variant e recuperare i dati inseriti.

<?php
$server = 'serverName';
$dbName = 'databaseName';
$uid = 'yourUserName';
$pwd = 'yourPassword';

$options = array("Database"=>$dbName, "UID"=>$uid, "PWD"=>$pwd);
$conn = sqlsrv_connect($server, $options);
if($conn === false) {
    die(print_r(sqlsrv_errors(), true));
}

$tableName = 'testTable';
$query = "CREATE TABLE $tableName ([c1_int] sql_variant, [c2_varchar] sql_variant)";

$stmt = sqlsrv_query($conn, $query);
if($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
}
sqlsrv_free_stmt($stmt);

$query = "INSERT INTO [$tableName] (c1_int, c2_varchar) VALUES (1, 'test_data')";
$stmt = sqlsrv_query($conn, $query);
if($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
}
sqlsrv_free_stmt($stmt);

$query = "SELECT * FROM $tableName";
$stmt = sqlsrv_query($conn, $query);

if(sqlsrv_fetch($stmt) === false) {
    die(print_r(sqlsrv_errors(), true));
}

$col1 = sqlsrv_get_field($stmt, 0);
echo "First field:  $col1 \n";

$col2 = sqlsrv_get_field($stmt, 1);
echo "Second field:  $col2 \n";

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

?>

L'output previsto è il seguente:

First field:  1
Second field:  test_data

Vedere anche

Riferimento all'API del driver SQLSRV

Procedura: Eseguire query con parametri

Informazioni sugli esempi di codice nella documentazione

Procedura: Inviare dati come flusso

Uso dei parametri direzionali