问题
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);
回答1:
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);
?>
来源:https://stackoverflow.com/questions/58788361/stored-procedures-work-fine-in-msql-studio-but-now-in-php