I\'ve looked over several other questions that seem (from the titles) the same as this. However, my case is a bit different.
The following works (i.e. I get \"succes
The user contributions on the php.net have a write up on how to execute a stored procedure using the sqlsrv-prepare.
In case that is removed from the php.net user contributions in the future here is what it had(has) listed:
$procedure_params = array(
array(&$myparams['Item_ID'], SQLSRV_PARAM_OUT),
array(&$myparams['Item_Name'], SQLSRV_PARAM_OUT)
);
// EXEC the procedure, {call stp_Create_Item (@Item_ID = ?, @Item_Name = ?)} seems to fail with various errors in my experiments
$sql = "EXEC stp_Create_Item @Item_ID = ?, @Item_Name = ?";
$stmt = sqlsrv_prepare($conn, $sql, $procedure_params);
Here's the manual's page, http://php.net/manual/en/function.sqlsrv-prepare.php
This is a follow up to the answer by @chris85.
It's worth noting here that once the statement is prepared, you need to execute it:
$sql = "EXEC stp_Create_Item @Item_ID = ?, @Item_Name = ?";
$stmt = sqlsrv_prepare($conn, $sql, $procedure_params);
if (!sqlsrv_execute($stmt)) {
echo "Your code is fail!";
die;
}
while($row = sqlsrv_fetch_array($stmt)){
//Stuff
}
sqlsrv_execute()
only returns true/false. If you want to parse the data returned by the stored procedure you can process it just like the result from sqlsrv_query()
.
If you forget the sqlsrv_execute()
you'll get an error saying that the result has to be executed before it can be used.
Make sure you set this or you will always get errors returned if the stored procedure has messages being returned.
sqlsrv_configure('WarningsReturnAsErrors',0);
//Full working code below
$sql = "{call NameOfDatabase.NameOfOwner.StoredProcedureName(?,?)}";
$params = array($param1, $param2);
if ($stmt = sqlsrv_prepare($conn, $sql, $params)) {
echo "Statement prepared.<br><br>\n";
} else {
echo "Statement could not be prepared.\n";
die(print_r(sqlsrv_errors(), true));
}
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}else{
print_r(sqlsrv_fetch_array($stmt));
}