LAST_INSERT_ID() MySQL

Viewed 412167

I have a MySQL question that I think must be quite easy. I need to return the LAST INSERTED ID from table1 when I run the following MySql query:

INSERT INTO table1 (title,userid) VALUES ('test',1); 
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(),4,1);
SELECT LAST_INSERT_ID();

As you can understand the current code will just return the LAST INSERT ID of table2 instead of table1, how can I get the id from table1 even if I insert into table2 between?

14 Answers

Instead of this LAST_INSERT_ID() try to use this one

mysqli_insert_id(connection)

For no InnoDB solution: you can use a procedure don't forgot to set the delimiter for storing the procedure with ;

CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
BEGIN
LOCK TABLES `table1` WRITE;
INSERT INTO `table1` ( `title` ) VALUES ( @title ); 
SET @id = LAST_INSERT_ID();
UNLOCK TABLES;
INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1); 
END

And you can use it...

SET @myid;
CALL myproc( @myid, 1, "my title" );
SELECT @myid;

In trigger BEFORE_INSERT this working for me:

SET @Last_Insrt_Id = (SELECT(AUTO_INCREMENT /*-1*/) /*as  Last_Insert_Id*/ 
FROM information_schema.tables 
WHERE table_name = 'tblTableName' AND table_schema = 'schSchemaName');

Or in simple select:

SELECT(AUTO_INCREMENT /*-1*/) as Last_Insert_Id
FROM information_schema.tables 
WHERE table_name = 'tblTableName' AND table_schema = 'schSchemaName'); 

If you want, remove the comment /*-1*/ and test in other cases. For multiple use, I can write a function. It's easy.

We could also use $conn->insert_id; // Create connection

    $conn = new mysqli($servername, $username, $password, $dbname);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if ($conn->query($sql) === TRUE) {
        $last_id = $conn->insert_id;
        echo "New record created successfully. Last inserted ID is: " . $last_id;
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

My code does not work for me. Any idea to recover the id of my last insert this is my code I am new developing and I do not know much

I GOT ERROR IN THE QUERY AND I DON'T KNOW HOW TO SEND PRINT IN THE LINE OF $ session-> msg ('s', "Product added successfully. Make cost configuration". LAST_INSERT_ID ());

ALREADY VERIFY AND IT IS CORRECT THE CONNECTION AND THE FIELDS OF THE DATABASE.

<?php
 if(isset($_POST['add_producto'])){
  $req_fields = array( 'nombre', 'categoria', 'proveedor');
   validate_fields($req_fields);
   if(empty($errors)){
     $codigobarras  = remove_junk($db->escape($_POST['codigobarras']));
     $identificador   = remove_junk($db->escape($_POST['identificador']));
     $nombre   = remove_junk($db->escape($_POST['nombre']));
     $categoria   =  (int)$db->escape($_POST['categoria']);
     $etiquetas   =  remove_junk($db->escape($_POST['etiquetas']));
     $unidadmedida   =  remove_junk($db->escape($_POST['unidadmedida']));
     $proveedor   =  remove_junk($db->escape($_POST['proveedor']));
     $fabricante   =  remove_junk($db->escape($_POST['idfabricante']));
     $maximo   =  remove_junk($db->escape($_POST['maximo']));
     $minimo   =  remove_junk($db->escape($_POST['minimo']));
     $descripcion   =  remove_junk($db->escape($_POST['descripcion']));
     $dias_vencimiento   =  remove_junk($db->escape($_POST['dias_vencimiento']));
      
     $servicio   = "0";
      if (isset($_POST['servicio'])){
        $servicio =implode($_POST['servicio']);
     }
     $numeroserie   = "0"; 
      if (isset($_POST['numeroserie'])){
        $numeroserie =implode($_POST['numeroserie']);
     }

     $ingrediente   =  "0";
      if (isset($_POST['ingrediente'])){
        $ingrediente =implode($_POST['ingrediente']);
     }

     $date    = make_date();
     $query  = "INSERT INTO productos (";
     $query .=" codigo_barras,identificador_producto,nombre,idcategoria,idetiquetas,unidad_medida,idproveedor,idfabricante,max_productos,min_productos,descripcion,dias_vencimiento,servicio,numero_serie,ingrediente,activo";
     $query .=") VALUES (";
     $query .=" '{$codigobarras}', '{$identificador}', '{$nombre}', '{$categoria}', '{$etiquetas}', '{$unidadmedida}', '{$proveedor}', '{$fabricante}', '{$maximo}', '{$minimo}', '{$descripcion}', '{$dias_vencimiento}', '{$servicio}', '{$numeroserie}', '{$ingrediente}', '1'";
     $query .=");";
     $query .="SELECT LAST_INSERT_ID();";

     if($db->query($query)){
      $session->msg('s',"Producto agregado exitosamente. Realizar configuracion de costos" . LAST_INSERT_ID());
       redirect('precio_producto.php', false);
     } else {
       $session->msg('d',' Lo siento, registro falló.');
       redirect('informacion_producto.php', false);
     }
   } else{
     $session->msg("d", $errors);
     redirect('informacion_producto.php',false);
   }
 }
?>
Related