PHP Data & APIs
advancedWhat You'll Learn
Theory
PHP is widely used for building data-driven web applications. It provides excellent support for databases, JSON processing, and API development.
PHP with Databases
PHP connects to databases using PDO (PHP Data Objects) — a consistent interface for multiple database types:
$pdo = new PDO(
"mysql:host=localhost;dbname=myapp",
$user, $password
);
$stmt = $pdo->prepare(
"SELECT * FROM users WHERE id = ?"
);
$stmt->execute([$id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);Prepared statements prevent SQL injection by separating query logic from data.
JSON APIs
PHP natively supports JSON with json_encode() and json_decode():
header("Content-Type: application/json");
$data = ["name" => "Alice", "age" => 25];
echo json_encode($data);Modern PHP Patterns
- MVC frameworks — Laravel, Symfony separate concerns
- Composer — dependency manager for PHP libraries
- PSR standards — PHP-FIG coding standards (PSR-4 autoloading, PSR-7 HTTP messages)
- Type declarations — PHP 7+ supports strict types for function parameters and return values
- Named arguments — PHP 8+ allows passing arguments by parameter name
Why this matters
Modern PHP development goes far beyond simple scripting. With PDO, JSON APIs, and frameworks like Laravel, PHP remains a powerful choice for building data-driven web applications and RESTful services.
What's next
In the next lessons, you'll dive deeper into each topic with hands-on examples and exercises.
Exercises
JSON Product API
Create a PHP script that defines an array of products (id, name, price), converts it to JSON, and outputs it with the correct Content-Type header.
Expected Output:
[{"id":1,"name":"Widget","price":9.99},{"id":2,"name":"Gadget","price":24.99},{"id":3,"name":"Doohickey","price":4.99}]