PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
236: Building an Inventory Management API
Imagine you're running a massive physical warehouse. You’ve got thousands of boxes, and you can't possibly let every single salesperson walk into the aisles and start counting things themselves—they'd trip over each other and probably lose half the stock. Instead, you hire a warehouse foreman. The foreman stands at a window. If a salesperson wants to know how many blue widgets are left, they hand the foreman a note. The foreman goes into the back, checks the shelf, and comes back with a written answer. If they want to add more stock, they hand over a delivery manifest, and the foreman updates the records.
In this lesson, your PHP code is that foreman. The "note" is the HTTP request, the "warehouse" is your database, and the "written answer" is the JSON response. You aren't building a website with buttons and colors; you're building a communication interface that other software can talk to.
Routing the Warehouse Requests
First, we need to figure out what the "note" is asking for. In a RESTful API, we use HTTP methods to define the action. I always tell my juniors to think of it as a verb. GET is "tell me," POST is "create this," PUT is "update this," and DELETE is "get rid of this."
// A simplified routing logic for our inventory
$method = $_SERVER['REQUEST_METHOD'];
$resource = $_GET['action'] ?? '';
switch ("$method:$resource") {
case 'GET:products':
handleGetProducts();
break;
case 'POST:products':
handleCreateProduct();
break;
case 'PUT:stock':
handleUpdateStock();
break;
default:
http_response_code(404);
echo json_encode(["error" => "Foreman doesn't know what that is."]);
break;
}
Validating the Manifest
Now, the foreman can't just trust every note he gets. If a salesperson hands him a note saying, "Add -500 widgets to the shelf," that's a problem. In PHP, when you're dealing with php://input (which is where the JSON body lives), you have to be ruthless about validation.
I've seen too many APIs crash because someone passed a string where an integer was expected. You need to decode the JSON and verify that the data is actually usable before it ever touches your database.
function handleUpdateStock() {
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['product_id']) || !isset($input['quantity'])) {
http_response_code(400);
echo json_encode(["error" => "Missing product ID or quantity."]);
return;
}
if (!is_int($input['quantity'])) {
http_response_code(400);
echo json_encode(["error" => "Quantity must be a whole number."]);
return;
}
// Now we can safely proceed to the database update...
}
Keeping the Count Honest
The core of inventory management isn't just adding or subtracting; it's ensuring you don't sell things you don't have. This is where your business logic lives. You shouldn't just run an UPDATE query blindly. You need to check the current stock level first, or better yet, use a SQL query that prevents the stock from dipping below zero.
Using a WHERE quantity >= :decrement clause in your update is a pro move. It prevents "race conditions" where two different API calls try to sell the last item at the exact same millisecond.
// Example of a safe stock deduction
$stmt = $pdo->prepare("UPDATE products SET quantity = quantity - :qty WHERE id = :id AND quantity >= :qty");
$stmt->execute(['qty' => $decrement, 'id' => $productId]);
if ($stmt->rowCount() === 0) {
http_response_code(409); // Conflict
echo json_encode(["error" => "Insufficient stock for this operation."]);
} else {
echo json_encode(["status" => "Stock updated successfully."]);
}
Talking Back in JSON
The most common mistake I see is PHP leaking a warning or an error message into the output, which breaks the JSON format and makes the client-side app crash. Your API should speak one language and one language only: JSON.
Always set your header at the very top of your script. This tells the receiving app, "Hey, don't treat this as a webpage; treat it as data."
header('Content-Type: application/json; charset=utf-8');
// Now everything you echo will be interpreted as JSON
📋 Practical Task
Build a "Low-Stock Alert" Endpoint
Your inventory API is working, but the warehouse manager is tired of checking every item manually. Your task is to create a new endpoint: GET /products/low-stock.
Requirements:
- The endpoint must accept an optional query parameter called
threshold(e.g.,?threshold=10). - If no threshold is provided, default the value to 5.
- The API should query the database and return a JSON array of all products where the current quantity is less than or equal to that threshold.
- Each product in the array should include the
product_name,sku, andcurrent_quantity. - Ensure you set the correct
Content-Typeheader and handle cases where no low-stock items are found (return an empty array, not an error).
There are no comments for now.