CodeIgniter Forums

Full Version: CI MySQLI Stored Procedure with Last Insert ID as output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am working with a very simple (or so I thought) process of passing a few inputs to a stored procedure, inserting a record, and then trying to get back the ID of that record that was inserted.

I just now realized that when calling a Stored Procedure, the insert_id is always 0. I have been bashing my head on the desk for a while with that one.

So, now I am trying to figure out how else to do it.

Model Function:

   public function addCustomerToProduct($data){
       $procedure = "CALL addCustomerProduct(?,?,@id)";
       $result = $this->db->query($procedure, $data);
       $newID = $this->db->query('SELECT @id as newID');
       echo $newID;

Stored Procedure:

CREATE DEFINER=`root`@`localhost` PROCEDURE `addCustomerProduct`(IN in_customerID INT, in_productID INT, OUT insertID INT)
    INSERT INTO order_customer_product (customerID, productID, retailAmountAtPurchase, faceValue)
        products as p
        p.productID = in_productID;
        SELECT LAST_INSERT_ID() as insertID;

This was my last attempt after reading some solutions line but then I get the error:

Commands out of sync; you can't run this command now

How can I resolve this to get the PK/AI that is generated by this stored procedure?
So, a couple things...

First, this is CI4 support and you're using $this->db-> syntax, so what version are you using/trying to get help for?

Second, that seems like an overly complicated way to do what you're trying to do, why not use the query builder( and then call $this->db->insert_id()?

Lastly, if you're determined to use MySQL like this, you may find someone here that can help but, you'd probably be better served asking in a MySQL forum.