sqlsrv_execute

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

sqlsrv_executeEjecuta una sentencia preparada con sqlsrv_prepare()

Descripción

sqlsrv_execute(resource $stmt): bool

Ejecuta una sentencia preparada con sqlsrv_prepare(). Esta función es ideal para ser ejecutar múltiples veces una sentencia preparada con diferentes valores de parámetros.

Parámetros

stmt

Un recurso de sentencia devuelto por sqlsrv_prepare().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 ejemplo de sqlsrv_execute()

Este ejemplo muestra como preparar una sentencia con sqlsrv_prepare() y reejecutarla múltiples veces (con diferentes valores de parámetros) utilizando sqlsrv_execute().

<?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 = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?"
;

// Inicializar los parámetros y preparar la sentencia.
// Las variables $qty y $id se pasan como parámetro a la sentencia $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !
$stmt ) {
die(
print_r( sqlsrv_errors(), true));
}

// Configurar la información de SalesOrderDetailID y OrderQty.
// Este array liga el orden ID al orden de cantidad en las parejas key=>value.
$orders = array( 1=>10, 2=>20, 3=>30);

// Ejecuta la sentencia para cada orden.
foreach( $orders as $id => $qty) {
// Como $id y $qty se pasan como parámetro a $stmt1, sus valores
// actualizados se utilizan en cada ejecución de la sentencia.
if( sqlsrv_execute( $stmt ) === false ) {
die(
print_r( sqlsrv_errors(), true));
}
}
?>

Notas

Cuando se prepara una sentencia que utiliza variables como parámetros, las variables se pasan como parámetros a la sentencia. Esto significa que si se actualizan los valores de las variables, la próxima vez que se ejecute la sentencia lo hará con los nuevos valores de los parámetros. Para las sentencias que se quieran ejecutar únicamente una vez, utilizar sqlsrv_query().

Ver también

add a note add a note

User Contributed Notes 3 notes

up
7
tuxedobob
8 years ago
If you're used to working with sqlsrv_query, you're probably used to the following flow:

<?php
$query
= "SELECT * FROM mytable WHERE id=?";
$result = sqlsrv_query($conn, $query, array($myID));
$row = sqlsrv_fetch_array($result);
?>

Given that, you might think the following works:

<?php
$myID
= 0;
$query = "SELECT * FROM mytable WHERE id=?";
$stmt = sqlsrv_prepare($conn, $query, array(&$myID));
$result = sqlsrv_execute($stmt);
$row = sqlsrv_fetch_array($result);
?>

It doesn't. The reason is that sqlsrv_execute, as noted above, returns true or false on success or failure, respectively. The variable that has your result is actually $stmt. Change the last row to

<?php
$row
= sqlsrv_fetch_array($stmt);
?>

and it works as expected.
up
1
esundberg at nitelusa dot com
4 years ago
Working PDO Prepare and Execute Example

Code
----------------------------------------
print "<h1>PDO Example</h1>";

print "<h2>PDO Connection</h2>";
try {
    $pdo = new PDO("sqlsrv:server=$sql_server;Database=$sql_database",$sql_username,$sql_password,['ReturnDatesAsStrings'=>true]);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
    die("Database Connection Error");
   
}

print "<h2>Check for PDO Connection</h2>";
if($pdo === false) {
    print "No DB Connection<br>";
} else {
    print "Good DB Connection<br>";
}

print "<h2>PDO Query Example 1 with SQL Injection</h2>";
print "I Personally prefer pdo due to binding of paramaters by name.<br>";
$sql = "SELECT username, active FROM users WHERE username = :username";
print "SQL: $sql\n";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username);
$stmt->execute();
while($r = $stmt->fetch(PDO::FETCH_OBJ)) {
    print_r($r);
}

------------------------------------------------------
PDO Example
PDO Connection
Check for PDO Connection
Good DB Connection
PDO Query Example 1 with SQL Injection
I Personally prefer pdo due to binding of paramaters by name.
SQL: SELECT username, active FROM users WHERE username = :username
stdClass Object
(
    [username] => admin
    [active] => 1
)
up
1
vavra at 602 dot cz
6 years ago
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.
To Top