我已经看到这个问题被问了很多次,但是他们都很长,我只是无法理解他们正在做的事情……所以,有人能告诉我如何获得LAST_INSERT_ID( )从这个程序到使用PDO的PHP:
表:
CREATE TABLE names (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,name varchar(50) NOT NULL
)
程序:
CREATE DEFINER=`root`@`localhost` PROCEDURE `simpleProcedure`(newname varchar(50),OUT returnid INT(11))
BEGIN
INSERT INTO names (name) VALUES (newname);
SET returnid = LAST_INSERT_ID();
END
$stmt=$db->prepare("CALL simpleProcedure(:name,:returnid)");
$stmt->bindValue(':name',$name,PDO::PARAM_STR);
$stmt->bindParam(':returnid',$returnid,PDO::PARAM_INT,11);
$stmt->execute();
echo $returnid;
但是,对于脑细胞比我更多的人来说,这可能是显而易见的.任何帮助赞赏.
参考我认为这应该工作的原因:
这是最初的错误报告:2005 through to 2013.这是新的错误报告:From 2013 to the present.
有多种方法可以获得答案,我找到了其中一个并证明了这一点……
‘技巧’是从’MysqL’程序获取输出.这是一个“两个阶段”的过程.
>第一部分是使用您的输入运行过程,并告诉它存储结果的MysqL变量.
>然后,运行单独的查询以“选择”那些“MysqL”变量.
这里有相当清楚的描述:php-calling-mysql-stored-procedures
更新(2017年1月):
这是一个示例,显示了’IN’,’INOUT’和’OUT’MysqL过程参数的变量的使用.
在我们开始之前,有一些提示:
>开发时:在“模拟模式”下运行PDO,因为它在确定过程调用中的错误时更可靠.
>仅将PHP变量绑定到过程’IN’参数.
当您尝试将变量绑定到INOUT和OUT参数时,您将获得一些非常奇怪的运行时错误.
像往常一样,我倾向于提供比所需更多的评论; – /
运行时环境(XAMPP):
源代码:
> SQL Procedure
> PHP with output
CREATE PROCEDURE `demoSpInOutsqlVars`(IN pInput_Param INT,/* PHP Variable will bind to this*/
/* --- */
INOUT pInOut_Param INT,/* contains name of the sql User variable that will be read and set by MysqL */
OUT pOut_Param INT) /* contains name of the sql User variable that will be set by MysqL */
BEGIN
/*
* Pass the full names of sql User Variable for these parameters. e.g. '@varInOutParam'
* These 'sql user variables names' are the variables that MysqL will use for:
* 1) finding values
* 2) storing results
*
* It is similar to 'variable variables' in PHP.
*/
SET pInOut_Param := ABS(pInput_Param) + ABS(pInOut_Param); /* always positive sum */
SET pOut_Param := ABS(pInput_Param) * -3; /* always negative * 3 */
END$$
数据库连接:
$db = appDIC('getDbConnection','default'); // get the default db connection
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
注意:输出与EMULATE_PREPARES = false相同.
设置将使用的所有PHP变量:
$PHPInParam = 5;
$PHPInOutParam = 404; /* PHP InOut variable ==> read and should be changed */
$PHPOutParam = null; /* PHP Out variable ==> should be changed */
$sql = "call demoSpInOut(:PHPInParam,@varInOutParam,/* MysqL variable name will be read and updated */
@varOutParam)"; /* MysqL variable name that will be written to */
$stmt = $db->prepare($sql);
> 1)绑定PHP变量
$stmt-> bindParam(‘:PHPInParam’,$PHPInParam,PDO :: PARAM_INT);
> 2)设置sql用户INOUT变量
$db-> exec(“SET @varInOutParam = $PHPInOutParam”); //这是安全的,因为它只是将值设置为MysqL变量.
执行程序:
$allOk = $stmt->execute();
$sql = "SELECT @varInOutParam AS PHPInOutParam,@varOutParam AS PHPOutParam
FROM dual";
$results = current($db->query($sql)->fetchAll());
$PHPInOutParam = $results['PHPInOutParam'];
$PHPOutParam = $results['PHPOutParam'];
注意:也许不是最好的方法; – /
"$PHPInParam:" => "5"
"$PHPInOutParam:" => "409"
"$PHPOutParam:" => "-15"