【问题标题】:PHP/mySQL Insert then get id by calling a stored procedurePHP/mySQL Insert 然后通过调用存储过程获取 id
【发布时间】:2014-06-23 19:39:22
【问题描述】:

我有一个 int 类型的 ID 字段,每当我插入一行时它就会自动递增。

当我这样做时,mysql_insert_id() 会获取插入的行

mysql_query("call AddUser($user,$pass);");

我想知道它是否会在调用存储过程时获取 ID。

【问题讨论】:

标签: php mysql stored-procedures mysqli insert


【解决方案1】:

如果您使用的是存储过程,那么您无法真正访问该过程中发生的事情,除非该过程本身将信息传递出去。因此,您可以为过程定义一个 OUT 参数并在其中返回 last_insert_id() 值:

程序

delimiter $$
drop procedure if exists p$$
CREATE PROCEDURE p(OUT InsertId int) 
BEGIN
insert test.Numbers (Numbers) values (3);
select last_insert_id() into InsertId ;

END$$
delimiter ;

使用 mysqli 查询调用

call p(@InsertId);

然后用另一个mysqli查询检索结果

select @InsertId as id;

注意 - 变量在连接的整个生命周期内都存在,因此除非您关闭连接,否则您可以在方便时检索 @InsertId 的值。

感谢 Patchrick 添加 PHP 细节:

$acct = mysql_query("call p(@InsertId);select @InsertId as id;");
$row = mysql_fetch_array($acct);
echo $row["id"]; 

【讨论】:

  • so 在 php 上使用时,$acct = mysql_query("call p(@InsertId); select @InsertId as id;"); $row = mysql_fetch_array($acct);回声 $row["id"];
  • 仅供参考 - 我发现我需要执行“选择 @InsertId 作为 id;”在 PHP7 中使用 mysqli 作为单独的 MySQL 查询调用。
猜你喜欢
  • 2016-03-28
  • 2016-10-19
  • 2011-03-13
  • 2020-06-07
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 2011-09-13
相关资源
最近更新 更多