← Back to PHP Course | Chapter 11: Database | Lesson 6 of 21

PHP Stored Procedures

Introduction to Stored Procedures

A stored procedure is a named block of SQL logic saved inside the database itself, which you can call from PHP by name instead of sending the full SQL text on every request.

Example: Introduction to Stored Procedures

php
<?php
// Stored procedures live in the database itself, e.g. MySQL:
// CREATE PROCEDURE GetUser(IN userId INT) BEGIN SELECT * FROM users WHERE id = userId; END
echo "A named block of SQL logic saved inside the database";
?>

Calling Stored Procedures

Calling a stored procedure from PHP typically looks like preparing and executing a CALL procedure_name(?, ?) statement, passing parameters the same way you would for any other prepared statement.

Example: Calling Stored Procedures

php
<?php
// $stmt = $pdo->prepare("CALL GetUser(?)");
// $stmt->execute([5]);
echo "Calling a stored procedure looks like any other prepared statement";
?>

Passing IN Parameters

Stored procedures can encapsulate multi-step logic (like validating and then inserting related rows across several tables) as a single atomic unit, reducing the number of round-trips between PHP and the database.

Example: Passing IN Parameters

php
<?php
// CALL CreateOrder(:userId, :productId) -- validates and inserts across multiple tables in one call
echo "One round-trip instead of several separate queries";
?>

Fetching OUT Parameters

Because the logic lives in the database rather than your PHP codebase, stored procedures are harder to version-control and test alongside your application code, which is a real tradeoff against their performance benefits.

Example: Fetching OUT Parameters

php
<?php
// Stored procedure logic lives in the database, separate from your PHP source files
echo "Harder to version-control alongside your application code";
?>

Fetching Multiple Result Sets

Modern PHP applications tend to favor keeping business logic in application code and using stored procedures more sparingly, reserving them for cases with a clear, specific performance or data-integrity need.

Example: Fetching Multiple Result Sets

php
<?php
// Most app logic stays in PHP; stored procedures are reserved for specific performance needs
echo "Use sparingly, for a clear, specific reason";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.