PHP MySQL: Call MySQL Stored Procedures

摘要在本教程中,您将学习如何使用 PHP PDO 调用 MySQL 存储过程。我们将向您展示如何调用返回结果集的存储过程以及接受输入/输出参数的存储过程。

调用返回结果集的存储过程

使用 PHP PDO 调用返回结果集的 MySQL 存储过程的步骤与使用 SELECT 语句从 MySQL 数据库表查询数据类似。您不是向 MySQL 数据库发送SELECT语句,而是发送存储过程调用语句。

首先,在示例数据库中创建一个名为GetCustomers()的存储过程以进行演示。 GetCustomers()  存储过程从customers表中检索客户的namecredit limit

以下GetCustomers()存储过程说明了该逻辑:

DELIMITER $$

CREATE PROCEDURE GetCustomers()
BEGIN
	SELECT customerName, creditlimit
	FROM customers;
    END$$Code language: SQL (Structured Query Language) (sql)

其次,创建一个名为phpmysqlstoredprocedure1.php的新 PHP 文件 使用以下代码

<!DOCTYPE html>
<html>
    <head>
        <title>PHP MySQL Stored Procedure Demo 1</title>
        <link rel="stylesheet" href="css/table.css" type="text/css" />
    </head>
    <body>
        <?php
        require_once 'dbconfig.php';
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
            // execute the stored procedure
            $sql = 'CALL GetCustomers()';
            // call the stored procedure
            $q = $pdo->query($sql);
            $q->setFetchMode(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            die("Error occurred:" . $e->getMessage());
        }
        ?>
        <table>
            <tr>
                <th>Customer Name</th>
                <th>Credit Limit</th>
            </tr>
            <?php while ($r = $q->fetch()): ?>
                <tr>
                    <td><?php echo $r['customerName'] ?></td>
                    <td><?php echo '$' . number_format($r['creditlimit'], 2) ?>
                    </td>
                </tr>
            <?php endwhile; ?>
        </table>
    </body>
</html>Code language: HTML, XML (xml)

除了 SQL 查询之外,一切都很简单:

CALL GetCustomers();Code language: SQL (Structured Query Language) (sql)

我们发送调用GetCustomers()的语句  MySQL 的存储过程。然后我们执行该语句来获取结果集。

第三,在 Web 浏览器中测试脚本以查看其工作原理。

php mysql stored procedure

您可以通过以下链接下载该脚本:

下载 PHP MySQL 存储过程源代码

使用 OUT 参数调用存储过程

使用OUT参数调用存储过程很棘手。我们将使用GetCustomerLevel()存储过程,该过程接受客户编号作为输入参数,并根据信用额度返回客户级别。

有关GetCustomerLevel()存储过程的详细信息,请查看MySQL IF 语句教程

DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(
    in  p_customerNumber int(11), 
    out p_customerLevel  varchar(10))
BEGIN
    DECLARE creditlim double;

    SELECT creditlimit INTO creditlim
    FROM customers
    WHERE customerNumber = p_customerNumber;

    IF creditlim > 50000 THEN
        SET p_customerLevel = 'PLATINUM';
    ELSEIF (creditlim <= 50000 AND creditlim >= 10000) THEN
        SET p_customerLevel = 'GOLD';
    ELSEIF creditlim < 10000 THEN
        SET p_customerLevel = 'SILVER';
    END IF;

END$$Code language: SQL (Structured Query Language) (sql)

在MySQL中,我们可以调用GetCustomerLevel()存储过程,如下所示:

CALL GetCustomerLevel(103,@level);
SELECT @level AS level;Code language: SQL (Structured Query Language) (sql)

在 PHP 中,我们必须模拟这些语句:

  • 首先,我们需要执行GetCustomerLevel()存储过程。
  • 其次,要获取客户级别,我们需要从变量@level进行查询。重要的是,我们必须调用PDOStatement对象的closeCursor()方法才能执行下一条 SQL 语句。

我们来看看如何在下面的PHP脚本中实现上述逻辑:

<?php

require_once 'dbconfig.php';

/**
 * Get customer level
 * @param int $customerNumber
 * @return string
 */
function getCustomerLevel(int $customerNumber) {
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

        // calling stored procedure command
        $sql = 'CALL GetCustomerLevel(:id,@level)';

        // prepare for execution of the stored procedure
        $stmt = $pdo->prepare($sql);

        // pass value to the command
        $stmt->bindParam(':id', $customerNumber, PDO::PARAM_INT);

        // execute the stored procedure
        $stmt->execute();

        $stmt->closeCursor();

        // execute the second query to get customer's level
        $row = $pdo->query("SELECT @level AS level")->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            return $row !== false ? $row['level'] : null;
        }
    } catch (PDOException $e) {
        die("Error occurred:" . $e->getMessage());
    }
    return null;
}

$customerNo = 103;
echo sprintf('Customer #%d is %s', $customerNo, getCustomerLevel($customerNo));Code language: PHP (php)

如果您在网络浏览器中测试脚本,您将看到以下屏幕截图:

php mysql 存储过程 OUT 参数

您可以通过以下链接下载该脚本:

下载带有 OUT 参数的 PHP MySQL 存储过程源代码

在本教程中,您学习了如何使用 PHP PDO 调用 MySQL 存储过程。

本教程有帮助吗?