Ever struggled with writing the same SQL queries over and over again in your code? I know I have! That’s where MySQL stored procedures come in to save the day. When I first discovered stored procedures after MySQL 5 was released, they completely transformed how I approach database programming.
In web development, especially with PHP, we’re used to writing raw SQL statements directly in our application code. While this works fine, it’s definitely not the most efficient approach. MySQL stored procedures offer a MUCH better alternative that will dramatically improve your database interactions.
A MySQL stored procedure is essentially a set of SQL statements stored within the database itself. Think of it as a function or method that lives in your database rather than your application code. You can call it whenever needed, passing parameters and getting results back.
Stored procedures offer several game-changing benefits:
Let’s dive right into creating a simple stored procedure in MySQL. I’ll show you how to do this using PHPMyAdmin, which most web developers are familiar with.
DELIMITER //
CREATE PROCEDURE check_number_type
(IN number_id INTEGER)
BEGIN
DECLARE name VARCHAR(10);
IF number_id % 2 = 0 THEN
SET name = 'even';
ELSE
SET name = 'odd';
END IF;
INSERT INTO number_table VALUES (number_id, name);
END //
DELIMITER ;
Code language: PHP (php)
This simple procedure takes a number as input, checks if it’s even or odd, and inserts the result into a table.
Let’s break down what’s happening in this procedure:
MySQL stored procedures can have three types of parameters:
Here’s an example with multiple parameter types:
DELIMITER //
CREATE PROCEDURE calculate_sum_and_difference
(
IN num1 INT,
IN num2 INT,
OUT sum_result INT,
OUT diff_result INT
)
BEGIN
SET sum_result = num1 + num2;
SET diff_result = num1 - num2;
END //
DELIMITER ;
Code language: JavaScript (javascript)
To call this procedure and get the results:
CALL calculate_sum_and_difference(10, 5, @sum, @diff);
SELECT @sum, @diff;
Code language: CSS (css)
Calling stored procedures from PHP is straightforward. Here’s how to do it:
<?php
// Connect to database
$conn = mysqli_connect("localhost", "username", "password", "database");
// For a simple procedure with one input parameter
$id = 5;
$result = mysqli_query($conn, "CALL check_number_type($id)");
// For a procedure with output parameters
mysqli_query($conn, "CALL calculate_sum_and_difference(10, 5, @sum, @diff)");
$result = mysqli_query($conn, "SELECT @sum, @diff");
$row = mysqli_fetch_assoc($result);
echo "Sum: " . $row['@sum'] . ", Difference: " . $row['@diff'];
mysqli_close($conn);
?>
Code language: HTML, XML (xml)
Once you’ve mastered the basics, you can explore more advanced features:
Beyond simple IF/ELSE, MySQL supports CASE statements:
DELIMITER //
CREATE PROCEDURE grade_student
(IN score INT)
BEGIN
DECLARE grade CHAR(1);
CASE
WHEN score >= 90 THEN SET grade = 'A';
WHEN score >= 80 THEN SET grade = 'B';
WHEN score >= 70 THEN SET grade = 'C';
WHEN score >= 60 THEN SET grade = 'D';
ELSE SET grade = 'F';
END CASE;
SELECT grade;
END //
DELIMITER ;
Code language: PHP (php)
MySQL procedures support several types of loops:
-- WHILE loop
DELIMITER //
CREATE PROCEDURE count_up
(IN max_num INT)
BEGIN
DECLARE counter INT DEFAULT 1;
WHILE counter <= max_num DO
SELECT counter;
SET counter = counter + 1;
END WHILE;
END //
DELIMITER ;
-- REPEAT loop (executes at least once)
DELIMITER //
CREATE PROCEDURE count_down
(IN start_num INT)
BEGIN
REPEAT
SELECT start_num;
SET start_num = start_num - 1;
UNTIL start_num <= 0
END REPEAT;
END //
DELIMITER ;
Code language: PHP (php)
MySQL provides DECLARE handlers for error conditions:
DELIMITER //
CREATE PROCEDURE safe_division
(IN numerator DECIMAL, IN denominator DECIMAL)
BEGIN
DECLARE result DECIMAL DEFAULT 0;
DECLARE div_error BOOLEAN DEFAULT FALSE;
-- Define error handler
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
SET div_error = TRUE;
-- Attempt division
IF denominator <> 0 THEN
SET result = numerator / denominator;
ELSE
SET div_error = TRUE;
END IF;
-- Return appropriate message
IF div_error THEN
SELECT 'Error: Cannot divide by zero' AS message;
ELSE
SELECT result AS result;
END IF;
END //
DELIMITER ;
Code language: PHP (php)
Based on my experience, here are some tips for working effectively with stored procedures:
Tip 💡: Explore more MySQL Best Practices!
While stored procedures are powerful, they do have some limitations:
Stored procedures are particularly useful in these scenarios:
MySQL stored procedures are an essential tool in any database developer’s toolkit. They offer significant advantages in terms of code organization, security, and performance. While they might seem intimidating at first, the skills you develop working with stored procedures will absolutely pay off in the long run.
I encourage you to start incorporating stored procedures into your MySQL projects. Even if you begin with simple cases, you’ll quickly see how they can streamline your database interactions and make your applications more maintainable.
Have you tried using MySQL stored procedures in your projects? What benefits or challenges have you encountered? I’d love to hear about your experiences in the comments!
Unlock the full potential of service workers with advanced features like push notifications, background sync, and performance optimization techniques that transform your web app into…
Learn how to integrate service workers in React, Next.js, Vue, and Angular with practical code examples and production-ready implementations for modern web applications.
Master the essential service worker caching strategies that transform web performance. Learn Cache-First, Network-First, and Stale-While-Revalidate patterns with practical examples that'll make your apps blazingly…
This website uses cookies.
View Comments
Hi, excellent article. I attach a post (the post is in Spanish, and the MySQL script's in Catalan) that explains how to implement a virtual store with MySQL stored procedures. There's a MySQL API there for typical CRUD operations. Greetings to all!
http://programarivm.com/2012/01/comercio-electronico-de-la-uoc-base-de-datos-de-una-tienda-virtual-con-stored-procedures-y-stored-functions-de-mysql/
HI, wery helpful post. Also for extended clarification I got some reference from http://www.techflirt.com/mysql-stored-procedure-tutorial/ . It was great pleasure to see sp in mysql as well.
Hi excellent post, I have a question, how do I get "out parameter" 's data of a Stored Procedure in PHP codeigniter. I use PDO and get success. but as I am basically a asp.net programmer So I cant understand " Using PDO is good for Codeigniter Framework or Not ?? ". Please help.. Thanks in advance.
I'm Sorry, i cant use SP in php codeigniter, i'm using driver mysql and php 5.
i can see error database then i call my SP, please help me!