SQLSRV stored procedure call not working - php

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?

Related

Getting error in executing Stored Proc from PHP

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)) {
}
...
?>

Call SQL Server stored procedure with output parameter from PHP

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

SQLSRV call a stored procedure in SQL server

I'm totally new at this, Just do 'cause of boss request. So i have some issue wanna ask.
This is result when i call SP in SQL
Below is code to calling a SP in php
$ma_dvcs = 'OL';
$ngay = '01/2/2015';
$ma_kho = 'BPOL01';
$ma_nhvt = '';
$ma_vt = '24110012A2140850';
$kieu = '1';
$query = "{call Tondaulist (#p_Ma_Dvcs_List = ?,#p_Ngay = ?,#p_Ma_Kho = ?,#p_Ma_Nh_Vt = ?,#p_Ma_Vt = ?,#p_Kieu = ?)}";
$params = array(
array(&$ma_dvcs, SQLSRV_PARAM_IN),
array(&$ngay, SQLSRV_PARAM_IN),
array(&$ma_kho, SQLSRV_PARAM_IN),
array(&$ma_nhvt, SQLSRV_PARAM_IN),
array(&$ma_vt, SQLSRV_PARAM_IN),
array(&$kieu, SQLSRV_PARAM_IN)
);
$smtp = sqlsrv_prepare($conn, $query, $params);
if( $smtp === false )
{
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true));
}
$rows = sqlsrv_execute($smtp);
var_dump($rows);die;
$arr[] = sqlsrv_fetch_array($rows,SQLSRV_FETCH_ASSOC);
SQLSRV exec var_dump return true but i cant fetch anything and it keep giving error:
The active result for the query contains no fields
Or
sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given
So i wanna know is SP working the same like function in php or not? If yes, can it return an array or can just return boolean and how to get that array?
Thank in advance
Try changing your query to this
$query = "EXEC Tondaulist #p_Ma_Dvcs_List = ?,#p_Ngay = ?,#p_Ma_Kho = ?,#p_Ma_Nh_Vt = ?,#p_Ma_Vt = ?,#p_Kieu = ?";
This won't return an "array" SQL doesn't support arrays, but it will return a result set
You also need to change the call sqlsrv_execute to sqlsrv_query
There's an example of looping through a SQL result set here PHP MSSQL - How To Loop through Returning Rows?
Hope that helps
You need to change code as i mention below.
use stmp as argument to method sqlsrv_fetch_array .
if(sqlsrv_execute($smtp)){
print "success";
while($row = sqlsrv_fetch_array($smtp)){
print_r($row);
print "<br />";
}
}else{
print_r( sqlsrv_errors());
}
if you still not able to do it let me know what problem you are facing with this code.

Retrive Param from SQL SERVER Query on PHP

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);
}
}

PHP: Param count and argument count don't match

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 );
}

Categories