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

sqlsrv_queryPrépare et exécute une requête


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

Prépare et exécute une requête.

Liste de paramètres


Une ressource de connexion retournée par la fonction sqlsrv_connect().


La chaîne qui définit la requête à préparer et à exécuter.


Un tableau spécifiant les paramètres lors de l'exécution d'une requête les autorisant. Les éléments du tableau peuvent être n'importe lequel parmi la liste ci-dessous :

  • Une valeur littérale
  • Une variable PHP
  • Un tableau avec cette structure : array($value [, $direction [, $phpType [, $sqlType]]])
La table suivante décrit les éléments dans la structure du tableau ci-dessus :

Structure du tableau
Élement Description
$value Une valeur littérale, une variable PHP ou une variable PHP par référence.
$direction (optional) Une des constantes SQLSRV suivantes utilisées pour indiquer la direction du paramètre : SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. La valeur par défaut est SQLSRV_PARAM_IN.
$phpType (optional) Une constante SQLSRV_PHPTYPE_* qui spécifie le type de données PHP de la valeur retournée.
$sqlType (optional) Une constante SQLSRV_SQLTYPE_* qui spécifie le type de données du serveur SQL pour la valeur en entrée.

Un tableau spécifiant les options de la requête. Les clés supportés sont décrites dans le tableau suivant :

Options de requête
Clé Valeur Description
QueryTimeout Une valeur entière positive. Définit le délai d'exécution maximal de la requête en seconde. Par défaut, le driver attendra indéfiniment les résultats.
SendStreamParamsAtExec TRUE ou FALSE (par défaut, vaut TRUE) Configure le driver pour envoyer tous les flux de données à l'exécution (TRUE) ou envoyer les flux de données en morceaux (FALSE). Pour plus d'informations, voir la fonction sqlsrv_send_stream_data().
Scrollable SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, ou SQLSRV_CURSOR_KEYSET Voir le chapitre sur » la spécification d'un type de curseur et la sélection de lignes dans la documentation Microsoft SQLSRV.

Valeurs de retour

Retourne une ressource de requête en cas de succès, et FALSE si une erreur survient.


Exemple #1 sqlsrv_query() example

$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password" );
$conn sqlsrv_connect$serverName$connectionInfo);
$conn === false ) {
print_rsqlsrv_errors(), true));

$sql "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1"some data");

$stmt sqlsrv_query$conn$sql$params);
$stmt === false ) {
print_rsqlsrv_errors(), true));


Pour les requêtes que vous ne prévoyez d'exécuter qu'une seule fois, utilisez la fonction sqlsrv_query(). Si vous souhaitez ré-exécuter une requête avec des valeurs différentes pour ses paramètres, utilisez la combinaison de la fonction sqlsrv_prepare() et de la fonction sqlsrv_execute().

Voir aussi

add a note add a note

User Contributed Notes 4 notes

bill_spam0001 at yahoo dot com
4 years ago
If you are getting an error while attempting to execute your query, and the output of sqlsrv_errors(SQLSRV_ERR_ERRORS) is this:

code: -14
message: An invalid parameter was passed to sqlsrv_query.

You have failed to pass a valid parameter to sqlsrv_query itself, which could be one of three parameters:
Connection: a valid handled for a SQL Server Connection
Query: a valid string containing your query, with placeholders for parameters:"(?)"
Parameters: An Array containing the values for your query parameters.  (optional, but much match the number of placeholders in your Query.

I could not find any information about this error, and it turned out to be a missing connection parameter. In my case I found I had typed "$connn" instead of "$conn" in the code:
if ($stmt=sqlsrv_query($conn, $sql, $params)) { ...

While this seems like a total "noobie" thing to do, the fact of the matter is there is very little information about this SQL Server Error message itself. So, the plain meaning of SQLSTATE "IMSSP", CODE "-14" is that you provided no valid connection object to your sqlsrv_query function.

This message may appear baffling, especially if you have several occurrences of sqlsrv_query on a page, and you may have added a new occurrence after you closed your connection.

Since I wasted an enormous amount of time tracing the normal channels, I thought referencing this error here would provide some help. In was hung up on "parameter" and was thinking it was a bad parameter object, and overlooked passing an undefined connection object to sqlsrv_query
bill_spam0001 at yahoo dot com
5 years ago
Tip: It may seem obvious, but you need to trim your strings down to fit in the database field you are saving them to via a parametrized query or a stored procedure. (IE: only submit up to 20 characters to a VARCHAR(20) database field). If you send a larger string to the query then it can handle, you will get an error.

When cleaning up your strings, you will most likely find yourself using the php substr() function. This function will return, as documented, a boolean FALSE value when presented with an empty string. Not minding this boolean FALSE value will cause "0" to be saved in your database tables instead of an empty string.

Since trimming your input is also important, the simple and intuitive solution for this is to trim your substr() output, which will consistently supply and empty string, not boolean FALSE.

So this will always work:
//trim last returns our empty string as a data type of string
$address_line_2 = trim(substr($_POST['addr2']),0,30));

gettype($address_line_2);  //outputs string

//executing a database query will save "" in field tblAddressBook.addr2
$sql = "update tblAddressBook set name=(?), addr1=(?), addr2=(?),..."
$params = array($name, $address_line_1, $address_line_2, ...)
$sql_srv_query($db_conn, $sql, $params);

This second way will give seemingly unexpected data in your database.
//if the result of trimming our post variable is "" (empty), substr() will return FALSE
$address_line_2 = substr(trim($_POST['addr2'])),0,30);

//$address_line_2 actually === FALSE, not ""
echo gettype($address_line_2);  //outputs boolean

//executing a database query will save "0" in field tblAddressBook.addr2
$sql = "update tblAddressBook set name=(?), addr1=(?), addr2=(?),..."
$params = array($name, $address_line_1, $address_line_2, ...)
$sql_srv_query($db_conn, $sql, $params);


You can also cast the type as a string using,
which will cast the boolean false back to the expected Empty String.

= (string)substr(trim($_POST['addr2'])),0,30);

gettype($address_line_2);  //outputs string

//executing a database query will save "" in field tblAddressBook.addr2
$sql = "update tblAddressBook set name=(?), addr1=(?), addr2=(?),..."
$params = array($name, $address_line_1, $address_line_2, ...)
$sql_srv_query($db_conn, $sql, $params);


I didn't notice this behavior until switching to IIS7, PHP 5.3.8 and SQL Server 2008.  But the behavior also is exhibited with IIS7, PHP 5.2 and SQL Server 2008.
vavra at 602 dot cz
5 days ago
If the sql contains INSERT, UPDATE or DELETE statements, the number of affected rows must be consumed. The sqlsrv_query returns a sql cursor that must be read to finish the transaction, if the result is non false. This same is valid for sqlsrv_execute. In this case the cursor must be also read using the prepared statement handle $smt.

Another solution is to place SET NOCOUNT ON at the top of the sqlsrv statement and all called procedures, functions and triggers.

We've practically observed it with sql statement with 500 inserts but only 368 was inserted without false returned. Prefixing by SET NOCOUNT ON or reading a cursor all rows were inserted.

See Processing Results (ODBC): https://docs.microsoft.com/en-us/sql/relational-databases/native-client-odbc-results/processing-results-odbc Each INSERT, UPDATE, and DELETE statement returns a result set containing only the number of rows affected by the modification. This count is made available when application calls SQLRowCount. ODBC 3.x applications must either call SQLRowCount to retrieve the result set or SQLMoreResults to cancel it. When an application executes a batch or stored procedure containing multiple INSERT, UPDATE, or DELETE statements, the result set from each modification statement must be processed using SQLRowCount or cancelled using SQLMoreResults. These counts can be cancelled by including a SET NOCOUNT ON statement in the batch or stored procedure.
oleg at mastak dot fi
5 years ago
If you hit an error "[Microsoft][ODBC Driver Manager] Invalid cursor state " when you specify valid Scrollable cursor, please check following bug report:


There is currently a bug that requires options Scrollable to be specified before QueryTimeout in corresponding array.
To Top