如何在php中使用pdo连接调用SQL Server存储过程?

5us2dqdw  于 2023-01-29  发布在  PHP
关注(0)|答案(1)|浏览(110)

我在SQL Server数据库中有两个存储过程getAllUsergetAllEvent()。我可以使用以下代码成功连接到数据库:

try {
    $hostname = "xxxxxx";
    $port = xxxx;
    $dbname = "xxxxx";
    $username = "xxxxx";
    $pw = "xxxxxx";
    $dbh = new PDO ("sqlite:server=$hostname;Database=$dbname","$username","$pw");
    echo "connected";
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }

现在我将如何调用这些存储过程....

  • getAllUser不需要任何参数
  • getAllEvent需要三个参数@FromDate@ToDate@UserID

怎么办?请帮帮忙

vojdkbi0

vojdkbi01#

您需要使用PDO::query()PDO::prepare()PDOStatement::execute()准备和执行PDO语句。
使用PDOStatement::bindParam()绑定参数。
使用CALL语法调用过程。
如果存储过程返回结果集,请使用PDOStatement::fetch()PDOStatement::fetchAll()获取数据:
接下来是使用PHP 7.1.12的工作示例,PHP驱动程序用于SQL Server 4.3.0 + 9904,SQL Server 2012 Express Edition。
T-SQL:

CREATE PROCEDURE [dbo].[getAllUser]
AS BEGIN
    SELECT 'Result from stored procedure.' AS [ResultText]
END

CREATE PROCEDURE [dbo].[getAllEvent]
     @FromDate date, 
     @ToDate date,
     @UserID int
AS 
BEGIN
    SELECT 
        @FromDate AS FromDate,
        @ToDate AS ToDate,
        @UserID AS UserID
END

PHP语言:

<?php
# Connection info
$hostname = 'server\instance,port';
$dbname   = 'database';
$username = 'username';
$pw       = 'password';

# Connection
try {
    $dbh = new PDO("sqlsrv:server=$hostname;Database=$dbname", $username, $pw);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
    die( "Error connecting to SQL Server. ".$e->getMessage());
}

# First procedure
try {
    echo "Procedure: getAllUser"."<br>";
    $sql = "{CALL getAllUser}";
    #$sql = "EXEC getAllUser";
    $stmt = $dbh->query($sql);
    # If your stored procedure returns information about records affected, fetch next result set
    $stmt->nextRowset();  
    while ($row = $stmt->fetch( PDO::FETCH_ASSOC )) {
       foreach($row as $name => $value) {
          echo $name.": ".$value."<br>";
       }    
    }
    echo "<br>";
} catch( PDOException $e ) {
    die( "Error executing stored procedure: ".$e->getMessage());
}
$stmt = null;

# Second procedure
try {
    echo "Procedure: getAllEvent"."<br>";
    $sql = "{CALL getAllEvent(?, ?, ?)}";
    #$sql = "exec getAllEvent ?, ?, ?";
    $fromDate = '2008-08-03'; 
    $toDate = '2008-08-05';
    $userID = 123;
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(1, $fromDate);
    $stmt->bindParam(2, $toDate);
    $stmt->bindParam(3, $userID);
    $stmt->execute();
    while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
        foreach($row as $name => $value) {
            echo $name.": ".$value."<br>";
        }   
    }
    echo "<br>";
} catch( PDOException $e ) {
    die( "Error connecting to SQL Server" );
}
$stmt = null;

# End
$dbh = null;
?>

相关问题