问题
I need to call a stored procedure to insert the data to sql and it return a value with output parameter
like
CREATE PROCEDURE InsertInfo
@userid VARCHAR(100),
@login_time DATETIME,
@IsSuccuess BIT,
@loginid INT OUTPUT
AS
BEGIN
INSERT INTO Audit_LoginLogoutAttempt(UserID,Login_Time, IsSuccuess, DateCreated) VALUES (@userid,@login_time,@IsSuccuess, GETDATE())
SET @loginid = @@IDENTITY
END
GO
How to send input and output parameters using PHP
$stmt = $conn->prepare("{CALL InsertInfo(?, ?, ?, ?)}");
$stmt->bindParam(1, $UserID);
$stmt->bindParam(2, $LoggedInDateTime);
$stmt->bindParam(3, $IsSuccuess);
$stmt->bindParam(4, $get_id, PDO::PARAM_INT, 32);
$stmt->execute();
echo $get_id;
I tried like this but I'm not getting desired value from $get_id
回答1:
You should bind your parameter as an OUTPUT parameter. If you have output parameters in your stored procedure and stored procedure returns recordsets, you need to fetch all recordsets to get output values.
<?php
# Statement
$stmt = $conn->prepare("{CALL InsertInfo(?, ?, ?, ?)}");
$stmt->bindParam(1, $UserID);
$stmt->bindParam(2, $LoggedInDateTime);
$stmt->bindParam(3, $IsSuccuess);
$stmt->bindParam(4, $get_id, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->execute();
# Fetch results. Include this if your procedure returns resultsets (usually from SELECT statements):
#do {
# while ($row = $stmt->fetch()) {
# //
# }
#} while ($stmt->nextRowset());
# Get OUTPUT parameter value
echo $get_id;
?>
I usually put SET NOCOUNT ON as first line in stored procedures. This prevents SQL Server from passing the count of rows affected as part of the result set.
CREATE PROCEDURE InsertInfo
@userid VARCHAR(100),
@login_time DATETIME,
@IsSuccuess BIT,
@loginid INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Audit_LoginLogoutAttempt(UserID,Login_Time, IsSuccuess, DateCreated) VALUES (@userid,@login_time,@IsSuccuess, GETDATE())
SET @loginid = @@IDENTITY
END
来源:https://stackoverflow.com/questions/53705953/call-sql-stored-procedure-from-php-pdo