I am trying to execute a sql server stored procedure from php. Stored procedure returns a output value. I want that value in php to display in webpage.
Everything works fine except the output value returns 0 in php.. but the row is getting inserted perfectly. the output value shows as 0. annoyed where I have made the mistake. Below is my php code
require('db.php');
$billno = "REF0001";
$retsno = 0.0;
$sp_name = "{call testinsert( ?, ? )}";
$params = array(
array($billno, SQLSRV_PARAM_IN),
array($retsno, SQLSRV_PARAM_OUT)
);
/* Execute the query. */
$stmt3 = sqlsrv_query( $conn, $sp_name, $params);
if( $stmt3 === false )
{
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true));
}
echo "Inserted Retuern Sno for ".$billno." is ". $retsno. ".";
and my stored procedure is
create procedure testinsert(#bill_no VARCHAR(20),#RetSno INT OUTPUT)
as
begin
insert into testable values(#bill_no,GETDATE())
set #RetSno = ##IDENTITY
return
end
Maybe you missed scrollable. https://msdn.microsoft.com/en-us/library/hh487160(v=sql.105).aspx
$stmt3 = sqlsrv_query( $conn, $sp_name, $params, array( "Scrollable" => 'static'));
Before you use your echo, add the following line to read the next line:
sqlsrv_fetch($stmt3);
Then you can select the first field of the response, which should be your parameter, with sqlsrv_get_field():
$id = sqlsrv_get_field(0);
I had the same case, and solved it using:
sqlsrv_next_result($stmt);
at the end of the instruction. Here I put part of my code in case it helps you.
$totalPaginas = 0;
$result = array();
$query = "EXEC DBO.SPS_EJECUTAR_CONSULTA #ReporteID = ?, #FilasPorPagina = ?, #NroPagina = ?, #TotalPaginas = ?";
$params = array(
array(&$reporteid, SQLSRV_PARAM_IN),
array(&$filasPorPagina, SQLSRV_PARAM_IN),
array(&$nroPagina, SQLSRV_PARAM_IN),
array(&$totalPaginas, SQLSRV_PARAM_OUT)
);
$stmt = sqlsrv_prepare($this->db, $query, $params);
if( !$stmt ) {
// show errors
}
$result = sqlsrv_execute($stmt);
if( !$result ) {
// show errors
}
$data = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$data[] = $row;
}
sqlsrv_next_result($stmt);
var_dum($data);
echo('Total Paginas: '.$totalPaginas);
Officially tells you how to do it here:
https://learn.microsoft.com/en-us/sql/connect/php/how-to-retrieve-input-and-output-parameters-using-the-sqlsrv-driver
Related
I am working on migrating our data from using inline SQL to using Stored Procedures. I am hitting a snag when running my code and getting the errors shown below:
Warning: sqlsrv_execute() expects parameter 1 to be resource, bool given in ajax_functions1.live.php on line 285
Warning: sqlsrv_fetch_array() expects parameter 1 to be resource, bool given in ajax_functions1.live.php on line 296
Below is an excerpt of the code:
function db_add_user($email, $provider, $subuid,$data){
include 'config.php';
$email = $data['preferred_username'];
$params = array(
array(&$myparams['email'], SQLSRV_PARAM_IN),
array(&$myparams['provider'], SQLSRV_PARAM_IN)
);
$sql = "{EXEC [dbo].[getSubUniqueID_HPCreate] #email = ?, #provider = ?}";
$stmt = sqlsrv_prepare($conn, $sql, $params);
sqlsrv_execute($stmt);
$uid=null;
if($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) > 0) {
$uid = $row[0]['sub_unique_id'];
}else{
$params = array(
array(&$myparams['email'], SQLSRV_PARAM_IN),
array(&$myparams['provider'], SQLSRV_PARAM_IN),
array(&$myparams['subuid'], SQLSRV_PARAM_IN)
);
$sql = "{EXEC [dbo].[insertSubUniqueID_HPCreate] #email = ?, #provider = ?, #subuid = ?}";
$stmt = sqlsrv_prepare($conn, $sql, $params);
sqlsrv_execute($stmt);
}
return $uid;
}
Here is the SP dbo.getSubUniqueID_HPCreate
USE [homepages_config]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[getSubUniqueID_HPCreate]
#email nvarchar(256),
#provider nvarchar(64)
AS
BEGIN
SET NOCOUNT ON;
SELECT sub_unique_id FROM homepages_config.dbo.users_providers
WHERE email = #email AND provider_id = #provider;
END
Here is the SP dbo.insertSubUniqueID_HPCreate
USE [homepages_config]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[insertSubUniqueID_HPCreate]
#email nvarchar(256),
#provider nvarchar(256),
#subuid nvarchar(1024)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO homepages_config.dbo.users_providers ([email], [provider_id], [sub_unique_id])
VALUES (LOWER(#email), #provider, #subuid)
END
Any help would be greatly appreciated.
First, the stored procedures are correct. One issue is the different declaration for the #provider parameter (#provider nvarchar(64) and #provider nvarchar(256)), but it's probably a typing error.
So, I think that you should make some changes in your script:
Execute the stored procedures with {call sp_name (?, ...)} syntax. This is a possible reason for the Warning: sqlsrv_execute() expects parameter 1 to be resource, bool given in ajax_functions1.live.php on line ... error, because function sqlsrv_prepare() is not executed correctly and you need to check the result from this execution. Note, that you may use sqlsrv_query(), because this function does both statement preparation and statement execution, and can be used to execute parameterized queries.
Change the parameters declaration for the db_add_user() function.
Always check for errors.
The result from sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) is an associative array, so $row[0]['sub_unique_id'] is an error.
The following script (based on your code) is a possible solution to your problem:
<?php
function db_add_user($email, $provider, $subuid){
include 'config.php';
$params = array(
array($email, SQLSRV_PARAM_IN),
array($provider, SQLSRV_PARAM_IN)
);
$uid = null;
$sql = "{call [dbo].[getSubUniqueID_HPCreate]( ?, ? )}"
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo print_r(sqlsrv_errors(), true);
return null;
}
if ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$uid = $row['sub_unique_id'];
} else {
$params = array(
array($email, SQLSRV_PARAM_IN),
array($provider, SQLSRV_PARAM_IN),
array($subid SQLSRV_PARAM_IN)
);
$sql = "{call [dbo].[insertSubUniqueID_HPCreate]( ?, ?, ? )}"
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo print_r(sqlsrv_errors(), true);
return null;
}
}
return $uid;
}
?>
I am new to MSSQL Server and there's a stored proc created by some developer and all I need to is run the proc from my PHP code.
But I am getting below error
The formal parameter "#contract_id" was not declared as an OUTPUT parameter, but the actual parameter passed in requested output.
Below is my code
$params['contract_id'] = '00990007';
$params['major_version'] = '1';
$procedure_params = array(
array(&$params['contract_id'], SQLSRV_PARAM_OUT),
array(&$params['major_version'], SQLSRV_PARAM_OUT)
);
$sql = "EXEC [MTP].[Process_07a_create_a_contract_version_wrapper] #contract_id = ?, #major_version = ?";
$stmt = sqlsrv_prepare($conn, $sql, $procedure_params);
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
if(sqlsrv_execute($stmt)){
while($res = sqlsrv_next_result($stmt)){
// make sure all result sets are stepped through, since the output params may not be set until this happens
}
// Output params are now set,
}else{
die( print_r( sqlsrv_errors(), true));
}
Can anyone guide me on this please?
First, check the type and the order of parameters, using sys.parameters. Then set params using the results:
<?php
...
$sql =
"SELECT [name], [is_output]
FROM sys.parameters
WHERE object_id = object_id('[MTP].[Process_07a_create_a_contract_version_wrapper]')
ORDER BY parameter_id";
$res = sqlsrv_query($conn, $sql);
if ($res === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC)) {
echo 'Name: '.$row['name'].', ';
echo 'Output: '.($row['is_output'] == 1 ? 'Yes' : 'No');
echo '</br>';
}
...
?>
Error message "The formal parameter "#contract_id" was not declared as an OUTPUT parameter, but the actual parameter passed in requested output" can be raised when the #contract_id parameter is not output parameter. So you can try with this (using your code):
<?php
...
$sql = "{call [MTP].[Process_07a_create_a_contract_version_wrapper](?, ?)}";
$procedure_params = array(
array($params['contract_id'], SQLSRV_PARAM_IN),
array(&$params['major_version'], SQLSRV_PARAM_INOUT)
);
$stmt = sqlsrv_query($conn, $sql, $procedure_params);
if( $stmt === false ) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
// Output parameters are available after consuming all resultsets.
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
}
...
?>
after read a bunch of threads, but i still dont know why my query not work :'(. It just return
sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given
sql connect is fine 'cause i can query select
already read this but no solution for this
Here my code
$ma_vt = '24110012A2140850';
$query = "{call dbo.Tondaulist(?,?,?,?,?,?)}";
$params = array(array('OL', SQLSRV_PARAM_IN),
array('01/02/2015', SQLSRV_PARAM_IN),
array('BPOL01', SQLSRV_PARAM_IN),
array('', SQLSRV_PARAM_IN),
array($ma_vt, SQLSRV_PARAM_INOUT),
array('1', SQLSRV_PARAM_IN)
);
$test = sqlsrv_query($conn, $query, $params);
if ($test === FALSE){
echo 'fail';
}
$arr = sqlsrv_fetch_array($test,SQLSRV_FETCH_ASSOC);
after an hour of trying, i changed my code like this
$query = "{call dbo.Tondaulist(?,?,?,?,?,?)}";
$params = array(array('OL,'),
array('01/02/2015'),
array('BPOL01'),
array(''),
array('24110012A2140850'),
array('1')
);
$smtp = sqlsrv_prepare($conn, $query, $params);
if ($smtp === FALSE){
echo 'fail';die;
}
sqlsrv_execute($smtp);
while($row = sqlsrv_fetch_array($smtp)){
echo 'ello';
echo '<br />';
}
if( sqlsrv_fetch_array( $smtp ) === false ) {
die( print_r( sqlsrv_errors(), true));
now stored procedure run but return error: The active result for the query contains no fields.
i run SP in SQL studio and it return 1 row.
this is my stored procedure's params
Anyone know where i was wrong?
I'm having a really annoying problem with a simple query.
So:
INSERT INTO [SapuV2].[dbo].[ALERGIA] ([DESCRIPCION]) OUTPUT INSERTED.PK_ALERGIA VALUES ('test')
PK_ALERGIA is a primary identity key, and i need the new id created.
PHP code:
$sql = "INSERT INTO ALERGIA (DESCRIPCION) OUTPUT INSERTED.PK_ALERGIA VALUES(?)";
$id = 0;
$params = array(
array(&$nombre, SQLSRV_PARAM_IN),
array(&$id, SQLSRV_PARAM_OUT, SQLSRV_PHPTYPE_INT)
);
$stmt = sqlsrv_prepare($this->Conn, $sql, $params);
if( sqlsrv_execute($stmt) === false){
die( print_r( sqlsrv_errors(), true) );
}else{
var_dump($id);
}
I'm able to save records on my BD, but $id is always 0 ...
Thanks ;)
Please try this:
INSERT INTO ALERGIA (DESCRIPCION)select #var=scope_identity()
I finally did it, but i'm not proud ...
Using same SQL Query, but change the sqlsrv_execute to a sqlsrv_fetch_array
$sql = "INSERT INTO ALERGIA ([DESCRIPCION]) OUTPUT INSERTED.PK_ALERGIA VALUES (?)";
$params = array(
array(&$nombre, SQLSRV_PARAM_IN)
);
$rows = sqlsrv_query($this->Conn, $sql, $params);
if($rows === false){
die(var_dump(sqlsrv_errors()));
}else{
while($row = sqlsrv_fetch_array($rows, SQLSRV_FETCH_ASSOC)){
var_dump($row);
}
}
My php application is using the MS SQLSrv driver. When making a call to a stored procedure in my database, I get the following error after running sqlsrv_execute(): param count and argument count don't match. My Code is as follows:
$sql = "{call myStoredProcedure(?, ?, ?, ?, ?, ?)}";
//Passing by reference instead of value, otherwise sqlsrv_prepare is not happy
$params = array(array(&$param1, SQLSRV_PARAM_IN),
array(&$param2, SQLSRV_PARAM_IN),
array(&$param3, SQLSRV_PARAM_IN),
array(&$param4, SQLSRV_PARAM_IN),
array(&$param5, SQLSRV_PARAM_IN),
array(&$param6, SQLSRV_PARAM_OUT)
);
/* Create the statement. */
$stmt = sqlsrv_prepare( $conn, $sql, $params);
if( $stmt )
{
echo "Statement prepared.\n";
}
else
{
echo "Error in preparing statement.\n";
die( print_r( sqlsrv_errors(), true));
}
//TODO: Resolve error, "param count and argument count don't match"
$stmt = sqlsrv_execute($conn, $sql, $params);
//This statement will run, but no rows are returned and rowCount is false.
//$stmt = sqlsrv_query($conn, $sql, $params);
$rowCount = sqlsrv_num_rows( $stmt );
$numFields = sqlsrv_num_fields( $stmt );
//Rest of code...
I've spent an hour on this and combed through PHP.Net and Microsoft documentation. Has anyone else encountered a similar error? Any help is appreciated.
And yes, I've checked my param count, my stored procedure takes 6 parameters.
UPDATE:
Stored procedure snippet:
ALTER PROCEDURE [dbo].[myStoredProcedure]
#param1 VARCHAR(64),
#param2 VARCHAR(64),
#param3 DATETIME,
#param4 DATETIME,
#param5 INT = 9,
#param6 INT OUTPUT
AS
BEGIN
//Do stuff
END
You are using SQLSRV_EXECUTE incorrectely. The error that your are getting is actually a PHP error, telling you that you are passing the wrong parameters to SQLSRV_EXECUTE.
Defined as:
sqlsrv_execute(resource $stmt)
But you are calling: sqlsrv_execute($conn, $sql, $params)
I've fixed up the code below, assuming the stored procedure is setup properly. Let me know if it works.
$sql = "{call myStoredProcedure(?, ?, ?, ?, ?, ?)}";
//Passing by reference instead of value, otherwise sqlsrv_prepare is not happy
$params = array(array(&$param1, SQLSRV_PARAM_IN),
array(&$param2, SQLSRV_PARAM_IN),
array(&$param3, SQLSRV_PARAM_IN),
array(&$param4, SQLSRV_PARAM_IN),
array(&$param5, SQLSRV_PARAM_IN),
array(&$param6, SQLSRV_PARAM_OUT)
);
/* Create the statement. */
$stmt = sqlsrv_prepare( $conn, $sql, $params);
if( $stmt )
{
echo "Statement prepared.\n";
}
else
{
echo "Error in preparing statement.\n";
die( print_r( sqlsrv_errors(), true) );
}
//Shouldn't assign this to $stmt, $stmt can be reused for multiple sqlsrv_execute() calls
$result = sqlsrv_execute($stmt);
if($result === false)
{
//Error handling
}
else
{
$rowCount = sqlsrv_num_rows( $result );
$numFields = sqlsrv_num_fields( $result );
}