Tuesday, 14 November 2017

HOW TO CALL STORED PROCEDURE IN CODEIGNITER

1. Create a stored procedure with no parameters.
In many cases, storing MySQL procedures to call on later is ideal if you do it more than once. Before you can call the procedure though you’ll need to create it, define the steps of the procedure. In this example, we’ll create a procedure that has no parameters to pass. The name of this MySQL procedure is Select_foo. We are pulling all the rows and all the fields in those rows from table creatively named table_foo.

CREATE PROCEDURE Select_foo ()
BEGIN
SELECT * FROM table_foo;
END
 
Now that the Select_foo procedure has been created and defined, we can call on this procedure at anytime in CodeIgniter. In this example, we create a variable, $data, by pointing to the procedure above after loading and initializing the database class in CodeIgniter.  


2. Create a stored procedure with a single parameter.
What if you want to depend on some parameter to run a procedure? For example, let’s say we want to remove all records in the table table_foo that have a value of 13 for some column called id, simply because we’re superstitious like that.
With a stored procedure that depends on parameters, we can use IN/OUT keyword for passing data into the procedure. Let’s create a stored procedure that will delete a record that has a specific id equal to a variable.
 
CREATE PROCEDURE delete_bar(IN p_id int(10))
BEGIN
DELETE FROM table_foo WHERE id=p_id ;
END
 
In parameterized stored procedure you can use IN/OUT keyword for passing the data to the procedure. After IN, we are stating that the parameter value we pass to the procedure delete_bar(), whatever sits between ( and ) will then be known as p_id, which we also state is an integer. The variable p_id doesn’t mean anything to us outside of the procedure delete_bar. But, now that we’ve created it, all we need to do is create a variable to call delete_bar() and have the procedure ask for a parameter, which can be done by inserting a ? between the parentheses that follow the procedure name.
So let’s create a set of variables, one that holds our number 13 and one that calls the procedure to delete rows with a specific id. Just so you know, you can pass a parameter to the procedure from either the model or the controller.

0 comments:

Post a Comment