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)) {
}
...
?>
Related
SQL Stored Procedure returns NULL when I call it from my mobile app or a web browser, but the same procedure returns what it has to when called using SQLPro for MSSQL software
if( $conn == FALSE ) {
echo "Connection failed.";
die( print_r( sqlsrv_errors(), true));
}
$query = "EXEC dbo.sp_Pok_Details #oe=17,#code='5907769000409'";
$getProducts = sqlsrv_query($conn, $query);
if ($getProducts == FALSE)
{
die(FormatErrors(sqlsrv_errors()));
}
while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC))
{
$returnArray[] = $row;
}
echo json_encode($returnArray);
Explanations:
You need to put SET NOCOUNT ON as first line in your stored procedure to prevent returning the number of rows affected by the T-SQL statements as part of the result set. This is the reason for your NULL results.
If you can't change your stored procedure, use sqlsrv_next_result() to make the next result active and then fetch the data.
As a note, always use prepared statements and parameterized queries to prevent SQL injection. With PHP Driver for SQL Server, function sqlsrv_query() does both statement preparation and statement execution and can be used to execute parameterized queries.
Example (based on your code):
<?php
if( $conn === false ) {
echo "Connection failed.";
die( print_r( sqlsrv_errors(), true));
}
$query = "EXEC dbo.sp_Pok_Details #oe = ?, #code = ?";
$params = array(17, '5907769000409');
$getProducts = sqlsrv_query($conn, $query, $params);
if ($getProducts === false) {
die( print_r( sqlsrv_errors(), true));
}
// Just for test - make additional call(s) to get the count of the active result sets
do {
while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC)) {
echo 'Current rowset'.'<br>';
}
} while (sqlsrv_next_result($getProducts));
// Or if you have only one result set
//while ($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC)) {
// $returnArray[] = $row;
//}
echo json_encode($returnArray);
?>
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
The last parameter '$status' is suppose to return a 0 or 1. How do I get the value of that output parameter? Echoing $result always returns 1. The stored procedure works under classic asp and .NET, but I need to do it under PHP.
$conn = sqlsrv_connect($serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$tsql = "{call spName(?,?,?,?)}";
$params = array(
array(&$param1, SQLSRV_PARAM_IN),
array(&$param2, SQLSRV_PARAM_IN),
array(&$param3, SQLSRV_PARAM_IN),
array(&$status, SQLSRV_PARAM_OUT)
);
$stmt = sqlsrv_prepare($conn, $tsql, $params);
if($stmt===false ) {
if( ($errors = sqlsrv_errors() ) != null) {
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_execute($stmt);
if($result === false){
die( print_r( sqlsrv_errors(), true));
}
echo " " . $result;
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
Unbelievable, all I had to do was echo the output parameter itself ($status in this example) to see the result.
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?
We would like to query our database and sample records based on a particular user's department.
Given the app design, the only way I know to do this is to filter the query by using dept's session variable.
The code below is not working.
Data gets returned if I comment out the session variable.
Nothing is getting retrieved with the session variable as filter.
Any ideas what I am doing wrong?
Is the session variable route the wrong approach?
Thanks in advance for help.
//Start your session
session_start();
// Connect to SQL Server database
include("../sqlConnect.php");
// Construct query
$loginName = $_GET['loginName'];
//Ok, let's grab user's dept from query
$sql = "SELECT ISNULL(dept,'NA') AS 'dept' FROM emp where ([userName]) = lower('$userName')"
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false )
{
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$results = array();
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) {
array_push($results,$row);
$dept = $row['dept'];
}
//Store department in the session
$_SESSION['dept'] = $dept;
//Now extract records based on dept
$tsql ="SELECT
r.REQUESTID,
convert(char(10),r.[currDate],101),
r.[startedDBY],
e.[dept],
e.[WORKPHONE],
e.[EMAIL],
r.[DESCRIPTION],
r.[DETAILS],
r.[PROBLOCATION],
c.[COMMENTS]'
FROM EMPLOYEE e,REQUEST r,CUSTOMERCALL c
WHERE LOGINNAME='$loginName'
AND c.REQUESTID=r.requestid
AND e.dept = '" . $_SESSION['dept'] . "'
";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$results = array();
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) {
array_push($results,$row);
}
echo json_encode($results);
// Free connection resources
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);