SQLSRV call a stored procedure in SQL server - php

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.

Related

Prepared Statements in MariDB

I'm fiddling around on my test database, learning how to set it all up.
I'm using PHP and PDO objects to access my database and get Data from it.
I'm also using prepared statements against MySQL Injections.
This is the code I'm using:
mainframe();
function mainframe(){
$connection = establishConnectionToDatabase();
$result = getData($connection);
//var_dump($result);
//echo json_encode($result);
echo $result;
}
function getData($connection){
$fetch = $connection->prepare("SELECT * FROM users_tbl");
$fetch->execute();
$result = $fetch->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
function establishConnectionToDatabase(){
try
{
$connection = new PDO('mysql:host=localhost;dbname=foundationtests',
'verwalter','test');
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $connection;
}
The table Im Accessing looks like this (see screenshot):
https://imgur.com/I06RF9e
When executing the above code, I'm only getting back
Notice: Array to string conversion in D:\foundationtests\src\assets\php\test.php on line 12
Array
I already tried out without prepared statements and it worked. I don't know what I'm missing.
You query is fine, you can't echo an array.
As you're returning an array, try this
function getData($connection){
$fetch = $connection->prepare("SELECT * FROM users_tbl");
$fetch->execute();
$result = $fetch->fetchAll(PDO::FETCH_ASSOC);
return (object)$result;
}
This will return your value as an object. Then you can echo whatever value using $result->user_id for example.
You can learn more about objects here
UPDATE
As has been pointed out, you can also just make it return as an object by change the 4th line from $result = $fetch->fetchAll(PDO::FETCH_ASSOC); to $result = $fetch->fetchAll(PDO::FETCH_OBJ);, and then changing the last line back to return $result;

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?

PHP MSSQL - sqlsrv stored procedure no error and no response

I created a microsoft sql stored procedure, and I am calling it from the php code below. I do not get any errors, but I do not get any output either. I have looked all over, but I am still fuzzy about how to do the WHILE statement to retrieve the variables I need from sql... I am hoping someone can take a look at the php code below (and the sql code below that) to see what I might be missing. Oh, and when I execute the stored procedure through SQL, it works fine and returns the data I expect. Thanks!
<?php
$serverName = "PRATHIBA-PC\SQL2008";
$connectionInfo = array( "Database"=>"TMS", "UID"=>"sa", "PWD"=>"asset12345" );
//$connectionInfo = array( "Database"=>"TMS");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Define the Transact-SQL query. Use question marks (?) in
place of the parameters to be passed to the stored procedure
*/
$tsql_callSP = "{call Getstudentname( 1 )}";
$studentid = '1';
$params = array(
array($studentid, SQLSRV_PARAM_IN)
);
/* Execute the query. */
$stmt3 = sqlsrv_query( $conn, $tsql_callSP, $params);
if( $stmt3 === false ) {
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true)); }
/* Display the value of the output parameters. */
while (sqlsrv_fetch_object($stmt3)) {
// SET PARAMETERS - SET TERMS
//echo $term;
}
/*Free the statement and connection resources. */
while ($obj=sqlsrv_fetch_object($stmt3)) {
// SET PARAMETERS - SET TERMS
echo $obj->term;}
sqlsrv_free_stmt( $stmt3);
?>
This is SQL Server stored procedure code
USE [TMS]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[Getstudentname]
SELECT 'Return Value' = #return_value
GO
When I run this code I am getting output:
exec Getstudentname 1;
this is my output in sql server
1 Vivek Johari vivek#abc.com
Please help me guys..
You could try using a question mark as a place-holder for the parameter like this:
$tsql_callSP = "{call Getstudentname(?)}";
Not sure if this will help?

how to execute sql server stored procedure on php?

i want to know why i cannot call any stored procedure on php file
it always return false
but when i call it on sql server directly, it shows my data
here is my php:
include ($_SERVER['DOCUMENT_ROOT'] . '/simda/classes/koneksi.php');
global $conn;
$kon = new koneksi();
$conn = $kon->bukaKoneksi();
$params = array();
$query = "EXEC dbo.RptSPJ_Pengeluaran '2013','1','1','1','0','1','1'";
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$rs_test = sqlsrv_query($conn, $query, $params, $options);
if ($rs_test != NULL) {
$num_rows = sqlsrv_num_rows($rs_test);
echo $num_rows;
}
else {
echo 'wrong';
}
if i echo the query and execute it on sql server, it shows my data
is there anything wrong?
please help me
thank you

Categories