从PHP PDO调用SQL存储过程

时间:2018-12-10 12:45:55

标签: php sql sql-server stored-procedures pdo

我需要调用存储过程以将数据插入sql并返回带有输出参数的值

喜欢

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

如何使用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;

我这样尝试过,但是我没有从$ get_id中获得期望的值

1 个答案:

答案 0 :(得分:2)

您应该bind将参数作为OUTPUT参数。如果存储过程中有输出参数,并且存储过程返回记录集,则需要获取所有记录集以获取输出值。

<?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 recordsets. Include this if your procedure returns recordsets (SELECT statements)
#do {
#   while ($row = $stmt->fetch()) {
#       // 
#   }
#} while ($stmt->nextRowset());


# Get OUTPUT parameter value
echo $get_id;

?>

我通常将SET NOCOUNT ON作为存储过程的第一行。这样可以防止SQL Server将受影响的行数作为结果集的一部分传递。

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