Search code examples
phpmysqlsqlstored-procedureslast-insert-id

Get last insert id from last inserted row


I'm here again and I'm getting crazy! I have this stored procedure:

CREATE DEFINER=`root`@`localhost` PROCEDURE `aggiungi_categoria`(IN   `id_categoria_principale` INT, IN `nome_categoria` VARCHAR(150), IN `sigla_categoria`    VARCHAR(10), IN `stato_categoria` INT) NOT DETERMINISTIC MODIFIES SQL DATA SQL SECURITY   DEFINER
begin

select @rgt := rgt,@lft := lft from categorie where id = id_categoria_principale;

if @rgt - @lft = 1 then

UPDATE categorie SET rgt = rgt + 2 WHERE rgt > @lft;
UPDATE categorie SET lft = lft + 2 WHERE lft > @lft;

insert into categorie (nome,sigla,stato,lft,rgt)
values(nome_categoria,sigla_categoria,stato_categoria,@lft+1,@lft+2);

 ELSE

 UPDATE categorie SET rgt = rgt + 2 WHERE rgt > @rgt-1;
 UPDATE categorie SET lft = lft + 2 WHERE lft > @rgt-1;

 insert into categorie (nome,sigla,stato,lft,rgt) values
(nome_categoria,sigla_categoria,stato_categoria,@rgt,@rgt+1);

 end if;


 end

how can i get the last insert id??? i tried all, with out param or doing a select with max(id) on the table or "set last_id = last_insert_id()" but i don't know how to get it via php?

when i call the procedure in phpmyadmin i'm getting something like

@rgt:=number,@lft:=number2

and in php obviously i get the same result in array.

what i'm doing wrong?


Solution

  • Ok i solved it!

    i added an int output parameter called last_id, before the end tag i included this statement:

    select last_insert_id() into last_id;
    

    In PHP i execute:

    $db -> execQuery('call aggiungi_categoria('.$parametri['id_categoria_principale'].',"'.$parametri['nome'].'","'.$parametri['sigla'].'",'.$parametri['stato'].',@lastId);');
    

    and finally

    $lid = $db ->execQuery('select @lastId;');