Welcome Guest, Not a member yet? Register   Sign In
CI MySQLI Stored Procedure with Last Insert ID as output
#1

(This post was last modified: 01-14-2018, 04:19 PM by sbbcarl.)

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:

 
Code:
   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:




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


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


Code:
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?
Reply
#2

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(https://codeigniter.com/user_guide/datab...ilder.html) and then call $this->db->insert_id()?

https://codeigniter.com/user_guide/datab...lpers.html

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB