Welcome Guest, Not a member yet? Register   Sign In
How to retrive Last inserted id ?
#1

[eluser]Rahul gamit[/eluser]
Hello,
I am using mysql storedprocedure for inserting the data into the database,
i want to retrive lastly inserted id of the row,
how to do this ??
Help me,
Thanks in advance...
#2

[eluser]jblack199[/eluser]
$this->db->insert_id()
#3

[eluser]Rahul gamit[/eluser]
$this->db->insert_id() gives the id when i am using $this->db->insert() function,
but when i am using stored procedure for inserting the data the $this->db->insert_id() gives 0 as output.
#4

[eluser]jblack199[/eluser]
Ok, I see what you mean.

I hope that you are using MySQL Query Browser, phpMyadmin has a problems using Stored Proedures properly.

So, within a MySQL Query Browser, right click - Create Stored Procedure
Give a name, let’s say ImportData
Then within a procedure put code like this:

Code:
DELIMITER $$

DROP PROCEDURE IF EXISTS `YourDB`.`ImportData`$$
CREATE DEFINER=`user`@`localhost` PROCEDURE `YourDB`.`ImportData` (
    IN val1Param INTEGER,
    IN val2Param INTEGER,
    IN category_idParam INTEGER
)
BEGIN
    DECLARE lastid INTEGER;
    INSERT INTO products(col1,col2) VALUES (val1Param,val2Param);
    SET lastid = (SELECT LAST_INSERT_ID());
    INSERT INTO products_categories (product, category) VALUES (lastid, category_idParam);  

END$$

DELIMITER ;


Execute it within MySQL Query Browser (button or alt+enter).
You can create Stored Procedure from a command line as well if you don’t like MySQL Query Browser.

IN val1Param INTEGER (and so on) are values that you are putting in the first table.
I have put INTEGER for example, but you must use exactly the same Data Type as is in your column.
Most probably your ID is INTEGER.

Once it is creating, calling Procedure is simple, within the model:
Code:
$q = "call ImportData($val1Param, $val2Param, $category_idParam)";  
$this->db->query($q);

Of course, you will put as many parameters you want within the procedure.
If your category_id needs to be taken from another table, use the same way - declare another variable within the stored procedure which will get this value.

That a little closer to what you are looking for?
#5

[eluser]Rahul gamit[/eluser]
yeah exactly i want this, thanks for your help jblack199 Smile




Theme © iAndrew 2016 - Forum software by © MyBB