Retrive Param from SQL SERVER Query on PHP - 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);
}
}

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 stored procedure call not working

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?

Grabbing last insert id sqlsrv

I am working on a php code where I insert into two tables and want to grab the id from the first table I inserted into, right now I am getting this error: Call to undefined function sqlsrv_field(). I am trying to grab the routine_id from the table routines.
Code:
date_default_timezone_set('Europe/Oslo');
$date = strftime ('%Y-%m-%d');
$time = strftime('%H:%M:%S');
$value = $_GET['Temp'];
$conn = sqlsrv_connect('BILAL' , $conn_array);
$sql = "Insert into routines (date, time, value, emp_id) values ('$date', '$time', '$value', (SELECT id FROM emps WHERE user_name='Arduino'))";
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$query = sqlsrv_query( $conn, $sql);
if( $query === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_next_result($query);
sqlsrv_fetch($query);
$id = sqlsrv_field($query,0);
$sql2 = "Insert into measure_routines (routine_id, measure_id, pool_id) values ('$id', (Select id from measurements where title='A_Auto_Temperatur'), 1 )";
$stmt = sqlsrv_query( $conn, $sql2);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
There is no function called sqlsrv_field(). Instead, use sqlsrv_get_field():
...
sqlsrv_next_result($query);
bool fetchStatus = sqlsrv_fetch($query);
if(fetchStatus === false) {
die( print_r( sqlsrv_errors(), true));
}
if(fetchStatus === null) {
// Some work when there are no results in the result set
} else {
$id = sqlsrv_get_field($query, 0);
}
...
This should solve your problem basically. However your code is vulnerable to SQL injection. Instead of giving values directly into the sql query, consider using prepared statements.
There are many articles about that, here is one I found in quick search:
What's the Right Way to Prevent SQL Injection in PHP Scripts?
Try this:
function lastId($queryID) {
sqlsrv_next_result($queryID);
sqlsrv_fetch($queryID);
return sqlsrv_get_field($queryID, 0);
}
$lastInsertedId = lastId($stmt);

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