Call SQL Stored Procedure from PHP PDO

孤者浪人 提交于 2021-01-28 05:18:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!