从PDO可调用语句获取out参数的正确方法

时间:2018-11-04 12:59:32

标签: php mysql pdo

我正在尝试在插入调用后返回out参数。我不知道如何更正我的PDO语法,使其返回新创建的部分的ID。

connection.php

$host = "127.0.0.1";
$db = "my_db";
$user = "root";
$pass = "";
$charset = "utf8";

$dsn = "mysql:host=$host; dbname=$db; charset=$charset";

try {
    $opt = [
        \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
        \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
        \PDO::ATTR_EMULATE_PREPARES => false,
    ];

    $pdo = new \PDO($dsn, $user, $pass, $opt);
}catch(Exception $e){
    $errorMessage = $e->getMessage();
    echo "<script type='text/javascript'>alert('$errorMessage');</script>";
}

daoimpl.php

function addNewSection(Section $section)
{
    //$isSuccessful = false;
    $outSectionId = 0;

    $sectionName = $section->getSectionName();

    $this->connection->beginTransaction();
    try {
        $sp_addNewSection = $this->connection->prepare('CALL addSection(?,@outSectionId)');
        $sp_addNewSection->bind_param('s',$sectionName);
        $sp_addNewSection->execute();

        //not sure how to do it correctly here
        $select = $this->connection->prepare('SELECT @outSectionId');
        $select->execute();
        $resultSet = $select->fetchAll(PDO::FETCH_ASSOC);
        $outSectionId = $resultSet['@outSectionId'];

        $this->connection->commit();
        //$isSuccessful = true;
    } catch (PDOException $e) {
        die($e->getMessage());
        $this->connection->rollback();
    }
        //return $isSuccessful;
    return $outSectionId;
}

addSection 存储过程

CREATE DEFINER=`root`@`localhost` PROCEDURE `addSection`(`pSectionName` VARCHAR(255), OUT opSectionId INT)
BEGIN

INSERT INTO section(section_name)
VALUES(pSectionName);

SELECT LAST_INSERT_ID() INTO opSectionId;

SELECT opSectionId;

END

重要的是,我需要将out参数部分的ID值返回给php,因为我将在事务块内添加更多查询。

我无法正常工作。如果我在MySQL Workbench中运行/调用存储的proc,则能够获取sectionId,但它在PHP中不起作用。

我将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试在您的过程中定义DELIMITER

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `addSection`(`pSectionName` VARCHAR(255), OUT opSectionId INT) BEGIN
    INSERT INTO section(section_name) VALUES(pSectionName);
    SELECT LAST_INSERT_ID() INTO opSectionId;
   SELECT opSectionId;
END $$
DELIMITER ;