How to get output values from a MS SQL stored procedure using PHP?

2k Views Asked by At

I have the following stored procedure on my MS SQL server:

CREATE PROCEDURE checkFollowing 
(
    @myMemberID INT,
    @otherMemberID INT
)
AS
BEGIN

IF EXISTS (SELECT 1 FROM Followers WHERE follower = @myMemberID AND followed = @otherMemberID)
    RETURN 1
ELSE
    RETURN 0    
END 
GO

In my PHP code I have this method so far:

function iAmFollowing($mymemberID, $otherMemberID) {
    $query = "EXEC checkFollowing @myMemberID = ?, @otherMemberID = ?";
    $stmt = sqlsrv_query($this->con, $query, array(&$mymemberID, &$otherMemberID));
    $result = sqlsrv_fetch_array($stmt);

    return $result[0];
}

As I have realised now, is that I can't get return values with the sqlsrv_fetch_array() command. But I canøt seem to figure out how to fetch the outpur value using php. Does someone know how to achieve this?

Any help will be gratly appreciated.

SOLUTION

CREATE PROCEDURE checkFollowing 
(
    @myMemberID INT,
    @otherMemberID INT
)
AS
BEGIN

IF EXISTS (SELECT 1 FROM Followers WHERE follower = @myMemberID AND followed = @otherMemberID)
    SELECT 1 AS 'output'
ELSE
    SELECT 0 AS 'output'    
END 
GO

And the php code should be almost the same. Just change the return value to: $result['output'];

1

There are 1 best solutions below

4
Pரதீப் On BEST ANSWER

Declare OUTPUT parameter in your SP's parameter list. The OUTPUT parameter return data back to the calling application. check this Link for more info

CREATE PROCEDURE checkFollowing 
(
    @myMemberID INT,
    @otherMemberID INT,
    @output INT OUTPUT
)
AS
BEGIN

IF EXISTS (SELECT 1 FROM Followers WHERE follower = @myMemberID AND followed = @otherMemberID)
    SELECT @output= 1
ELSE
    SELECT @output= 0    
END 
GO

Update:

To Call the SP and to store the Output. Try something like this

DECLARE @appout int; -- variable to hold the data returned by SP.

EXEC checkFollowing 10,20, @output = @appout OUTPUT; -- This is how i will call a SP.

@appout - will hold the data returned by the procedure.