Friday 13 July 2018

PHP MySQL: Call MySQL Stored Procedures

PHP MySQL: Call MySQL Stored Procedures?

Summaryin this tutorial, you will learn how to call MySQL stored procedures using PHP PDO. We will show you how to call stored procedures that return a result set and stored procedures that accept input/output parameters.

Calling stored procedures that return a result set

The steps of calling a MySQL stored procedure that returns a result set using PHP PDO are similar to querying data from MySQL database table using the SELECT statement. Instead of sending a SELECTstatement to MySQL database, you send a stored procedure call statement.
First, create a stored procedure named GetCustomers()  in the sample database for the demonstration. The GetCustomers()  stored procedure  retrieves the name and credit limit  of customers from the customers table.
The following GetCustomers() stored procedure illustrates the logic:
Second, create a new PHP file named  phpmysqlstoredprocedure1.php  with the following code:
Everything is straightforward except the SQL query:
We send the statement that calls the  GetCustomers()  stored procedure to MySQL. And we execute the statement to get a result set.
Third, test the script in the web browser to see how it works.

You can download the script via the following link:

Calling stored procedures with an OUT parameter

It is a little bit tricky to call a stored procedure with the OUT parameter. We will use the GetCustomerLevel()  stored procedure that accepts a customer number as an input parameter and returns the customer level based on credit limit.
Check the MySQL IF statement tutorial for detailed information on the GetCustomerLevel()  stored procedure.
In MySQL, we can call the GetCustomerLevel()  stored procedure as follows:
In PHP, we have to emulate those statements:
  • First, we need to execute the GetCustomerLevel()  stored procedure.
  • Second, to get the customer level, we need to query it from the variable @level . It is important that we must call the method closeCursor()  of the PDOStatement  object in order to execute the next SQL statement.
Let’s take a look at how the logic is implemented in the following PHP script:
If you test the script in the web browser, you will see the following screenshot:

You can download the script via the following link:
In this tutorial, you have learned how to call MySQL stored procedures using PHP PDO.

0 comments:

Post a Comment