Wednesday, March 10, 2010

creating MYSQL stored procedure and calling it from PHP

# Open phpMyadmin.
# Select a database to work with.
# Open the SQL tab.

Assume your database contains table called employees.

In the SQL tab,
you can start writing :

DROP PROCEDURE IF EXISTS listEmployees $$
CREATE PROCEDURE listEmployees()
BEGIN
select * from employees;
END $$

In delimiter [;] change ; to $$.

Hit go. Thats it, you are done with creating your first stored procedure.



Up to this anyone can google and create the stored procedure, but big mess is how to use this in PHP.
After many trails and trails I learned how to call procedure in php.


Normally you would use the below to connect to a mysql database in php.
$connector=mysql_connect(host,user,pass);

In order to use stored procedures try connecting like this:

$connector=mysql_connect(host,user,pass,true,65536);
mysql_select_db(database,$connector); //Nothing changes here

Now you are done with making php mysql to use with stored procedure.

Lets see how you can call stored procedure with php.

$query=mysql_query("CALL listEmployees()");
while($result=mysql_fetch_array($query))
{
echo $result[emp_name]."
";
}

Thats it. It calls procedure called listEmployees(which we written above and that does lists all employees data from employee table).

No comments:

Post a Comment