简体   繁体   中英

Call SQL Stored Procedure from PHP PDO

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM