PHP MySQL:调用MySQL存储过程

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

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

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

首先,在示例数据库中创建一个名为GetCustomers()的存储过程进行演示。
GetCustomers()存储过程从客户表中检索客户的名称和信用额度。

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

DELIMITER $$

CREATE PROCEDURE GetCustomers()
BEGIN
	SELECT customerName, creditlimit
	FROM customers;
    END$$

其次,使用以下代码创建一个名为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>

除SQL查询外,其他一切都很简单:

CALL GetCustomers();

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

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

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

下载PHP MySQL存储过程源代码

使用OUT参数调用存储过程

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

查看MySQL IF语句教程以获取有关GetCustomerLevel()存储过程的详细信息。

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$$

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

CALL GetCustomerLevel(103,@level);
SELECT @level AS level;

在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));

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

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

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

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

日期:2019-11-20 08:52:37 来源:oir作者:oir