Thursday, June 21, 2012

How to call stored procedure in codeigniter?


Step to do:

To call stored procedure in codeigniter follow the steps.
1. Create parameter less Stored procedure
for eg
CREATE PROCEDURE Select_all ()
BEGIN
 SELECT * FROM table_name;
END

To call this procedure,

$sp_data = $this->db->query("CALL Selct_all()");
$result = $sp_data->result();

So to call the stored procedure "CALL" keyword is used followed by the procedure name.
$result contains the all the records for table_name , you can return $result as per your need.

2. Create Parametrized Stored Procedure

eg.

CREATE PROCEDURE delete_single(IN p_id  int(10))
BEGIN
DELETE FROM table_name WHERE  id=p_id ;
END

In parametrized stored procedure you can use IN/OUT  keyword for passing the data in to the procedure.
here p_id is the parameter passed for the procedure delete_single()

To call the parametrized stored procedure you have to pass the parameter from the model or the controller.
 $id = '1';
$stored_procedure = "CALL delete_single(?) ";
$result = $this->db->query($stored_pocedure,array('id'=>$id));

If you want to pass 3 variable then you have to use 3 times ? with comma separated.
eg "CALL test_procedure(?,?,?)";
To pass the value for the procedure you have to use the array, for example for 3 parameter
eg $stored_procedure = "CALL test_procedure(?,?,?)";
$this->db->query($stored_procedure,array('id'=>'1','name'=>'test','address'=>'abc'));

so like this you can call both the type of stored procedure.

No comments:

Post a Comment