PHP.mk документација

sqlsrv_query

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.sqlsrv-query.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.sqlsrv-query.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
sqlsrv_query

Референца за `function.sqlsrv-query.php` со подобрена типографија и навигација.

function.sqlsrv-query.php

sqlsrv_query

(Нема достапни информации за верзијата, можеби е само во Git)

sqlsrv_queryПодготвува и извршува барање

= NULL

sqlsrv_query(
         resource $conn,
         string $sql,
         array $params = ?,
         array $options = ?
): mixed

Подготвува и извршува барање.

Параметри

conn
Подготвува прашалник за извршување. Оваа функција е идеална за подготовка на прашалник што ќе се извршува повеќе пати со различни вредности на параметрите. sqlsrv_connect().
sql
Ресурс за конекција вратен од
params

Низата што го дефинира прашалникот што треба да се подготви и изврши.

  • Низа што специфицира информации за параметрите при извршување на параметарски прашалник. Елементите на низата можат да бидат било што од следново:
  • Буквална вредност
  • An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
PHP променлива
Следната табела ги опишува елементите во горната структура на низата:
Елемент = NULL
$value Структура на низа
$direction (optional) Буквална вредност, PHP променлива или PHP променлива по референца.
$phpType (optional) Една од следниве SQLSRV константи за означување на насоката на параметарот: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. Стандардната вредност е SQLSRV_PARAM_IN.
$sqlType (optional) SQLSRV_PHPTYPE_* константа што специфицира PHP тип на податоци на вратената вредност.
options
SQLSRV_SQLTYPE_* константа што специфицира SQL Server тип на податоци на влезната вредност.
Низа што специфицира опции за својства на прашалникот. Поддржаните клучеви се опишани во следната табела:
Можни индекси на низи за Режими на календар = NULL
QueryTimeout Опции за прашалник Позитивен цел број.
SendStreamParamsAtExec true or false Поставува временско ограничување на прашалникот во секунди. Стандардно, драјверот ќе чека неодредено време за резултати. true) (стандардно еtrueКонфигурира драјверот да испраќа сите податоци од стримот при извршување (false). Стандардно, вредноста е поставена на true. За повеќе информации, видете sqlsrv_send_stream_data().
Подвижно SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, или SQLSRV_CURSOR_KEYSET Константи за известување за грешки Укажува на курсор само напред. За информации за употреба, видете во документацијата на Microsoft SQLSRV.

Вратени вредности

Враќа ресурс за изјава при успех и false аргумент, или

Примери

Пример #1 sqlsrv_query() example

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

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

$stmt = sqlsrv_query( $conn, $sql, $params);
if(
$stmt === false ) {
die(
print_r( sqlsrv_errors(), true));
}
?>

Белешки

За изјави што планирате да ги извршите само еднаш, користете sqlsrv_query(). Ако имате намера повторно да извршите изјава со различни вредности на параметрите, користете ја комбинацијата од sqlsrv_prepare() and sqlsrv_execute().

Види Исто така

  • sqlsrv_prepare() - Подготвува прашалник за извршување
  • sqlsrv_execute() - Извршува изјава подготвена со sqlsrv_prepare

Белешки од корисници 6 белешки

bill_spam0001 на yahoo точка com
12 години пред
If you are getting an error while attempting to execute your query, and the output of sqlsrv_errors(SQLSRV_ERR_ERRORS) is this:

SQLSTATE: IMSSP
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
suconghou на gmail точка com
пред 8 години
Attention!
 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.
bill_spam0001 на yahoo точка com
пред 14 години
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: 
<?php 
//trim last returns our empty string as a data type of string
$address_line_2 = trim(substr($_POST['addr2']),0,30));

echo 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.
<?php 
//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. 
<?php 

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

echo 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.
phil на dier точка us
пред 13 години
If you hit an error "[Microsoft][ODBC Driver Manager] Invalid cursor state " when you specify valid Scrollable cursor, please check following bug report:

https://bugs.php.net/bug.php?id=63498

There is currently a bug that requires options Scrollable to be specified before QueryTimeout in corresponding array.
anon на example dot com
пред 7 години
Note that you can get multiple results when executing a single query, for example:

    <?php
    $stmt = sqlsrv_query($conn, "use dbname; select 1");
    ?>

Running the same query in tsql or management studio works as expected. However, with sqlsrv_* functions, this gives you two result sets -- one for the "use" and one for the "select".

    <?php
    // Advance the result pointer from "use" to "select"
    sqlsrv_next_result($stmt);

    // Now you can read the "1"
    print_r(sqlsrv_fetch_array($stmt));
    ?>

For a complex query that begins by creating/populating temporary tables, you will need to advance the result pointer past such statements to get data from the final select statement. In older PHP versions (using FreeTDS-based mssql connectivity at least), you'd get only the last result so didn't need to take this into account.
erikpsundberg на gmail точка com
пред 6 години
2 Working Example

print "<h1>SQL Query non PDO</h1>";
print "<h2>Connection</h2>";
$connectionInfo = array( "Database"=>$sql_database, "UID"=>$sql_username, "PWD"=>$sql_password );
$conn = sqlsrv_connect( $sql_server, $connectionInfo);

if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
} else {
    print "Good DB Connection: $conn<br>";
}

print "<h2>Query Example 1 | Fetching by Associate Array</h2>";
$sql = "SELECT username, active FROM users WHERE username = '$username'";
print "SQL: $sql\n";
$result = sqlsrv_query($conn, $sql);
if($result === false) {
    die(print_r(sqlsrv_errors(), true));
}
#Fetching Data by array
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
    print_r($row);
}

print_line();
print "<h2>Query Example 2 | injection protection | Fetching by Object</h2>";
$sql = "SELECT username, active FROM users WHERE username = ?";
print "SQL: $sql\n";
$result = sqlsrv_query($conn, $sql, array($username));
if($result === false) {
    die(print_r(sqlsrv_errors(), true));
}
#Fetching Data by object
while($row = sqlsrv_fetch_object($result)) {
    print_r($row);
}

--------------------------------------------------
Result

Connection
Good DB Connection: Resource id #2
Query Example 1 | Fetching by Associate Array
SQL: SELECT username, active FROM users WHERE username = 'admin'
Array
(
    [username] => admin
    [active] => 1
)
######################################################################
Query Example 2 | injection protection | Fetching by Object
SQL: SELECT username, active FROM users WHERE username = ?
stdClass Object
(
    [username] => admin
    [active] => 1
)
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.