CHAPTER 21
Beginner
Connecting REST APIs with MySQL
Updated: May 13, 2026
5 min read
# CHAPTER 21
Connecting REST APIs with MySQL
1. Introduction
An API without a database is just a calculator. To build real applications, you need persistent storage. In Chapter 21, we will integrate MySQL into the PHP routing engine we built in the previous chapter. We will use PHP Data Objects (PDO) to securely connect to the database, execute queries, and format the SQL results directly into JSON arrays.2. Learning Objectives
By the end of this chapter, you will be able to:- Establish a secure PDO connection to a MySQL database.
- Use PDO Prepared Statements to prevent SQL injection.
- Fetch database records and output them as JSON arrays.
- Insert new records from a JSON API payload into MySQL.
- Handle database connection errors gracefully without leaking credentials.
3. Beginner-Friendly Explanation
Think of PDO as a highly trained translator. PHP speaks one language, and MySQL speaks another. If PHP tries to talk to MySQL directly using raw strings, it is dangerous and prone to misunderstandings (SQL injection). PDO sits between them. You hand PDO your data securely, and PDO translates it into a perfectly safe, optimized command that MySQL understands. Furthermore, when MySQL replies with a table of data, PDO neatly packages it into a PHP array, which you can then instantly convert into JSON.4. Real-World Examples
-
Fetching Users:
GET /userstells PHP to ask PDO to runSELECT * FROM users. PDO returns an array of users, and PHPjson_encodes it back to the client.
-
Creating a Post:
POST /poststakes the JSON payload, gives the variables to PDO, and PDO runsINSERT INTO posts...
5. Detailed Code Examples
Let's look at a complete, secure database connection and a basic GET/POST implementation.1. The Database Connection (db.php):
php
2. Integrating PDO into the API:
php
6. Request/Response Examples
GET /users Response: Notice how the database columns map perfectly to the JSON keys because we usedPDO::FETCH_ASSOC.
json
7. HTTP Examples
The API now fully connects the HTTP method to the database logic:-
GETtriggers$pdo->query()or$stmt->fetchAll().
-
POSTtriggers$pdo->prepare(INSERT...)and$pdo->lastInsertId().
-
DELETEtriggers$pdo->prepare(DELETE...)and$stmt->rowCount()to see if a row was actually deleted.
8. JSON Examples
When updating data, you check if the database actually changed anything.
php
9. Best Practices
-
PDO::FETCHASSOC: Always set this as your default fetch mode. It forces PDO to return arrays with column names as keys (['name' => 'Alice']), whichjsonencodeperfectly translates into JSON objects.
-
Never expose passwords: When selecting data (e.g.,
SELECT * FROM users), explicitly name the columns you want (SELECT id, name, email). If you use*, you might accidentallyjsonencodethe user's hashed password and send it to the frontend!
10. Common Mistakes
-
mysqlivsPDO: Beginners often use the oldermysqliqueryfunctions. PDO is highly preferred for APIs because it allows named parameters (:name) and returns clean arrays perfectly suited for JSON.
-
Leaking DB Errors: If a SQL query fails (e.g., a duplicate email), PDO throws an exception. If you don't catch it, PHP outputs an HTML error. You must wrap your
execute()intry...catchblocks to return a clean JSON500or400error.
11. Mini Exercises
-
1.
Look at this bad code:
$pdo->query("SELECT * FROM users WHERE name = '" . $GET['name'] . "'");. Why is this incredibly dangerous?
'; DROP TABLE users;-- in the URL and delete the database).*
12. Coding Challenges
Challenge 1: Write the PDO logic forDELETE /users/5. Prepare the statement, bind the ID, execute it, and return a JSON message confirming deletion.
13. MCQs with Answers
Question 1
What PHP extension is the industry standard for connecting to databases in modern APIs?
Question 2
Why is PDO::FETCHASSOC the best fetch mode for REST APIs?
Question 3
How do you safely insert API JSON data into MySQL?
14. Interview Questions
- Q: Explain why Prepared Statements are mandatory when building APIs that accept user data.
-
Q: If a PDO connection fails, why is it a security risk to output the raw
PDOExceptionmessage to the API client?
-
Q: Describe how you handle the output of
PDO::lastInsertId()in a REST API POST response.
15. FAQs
Q: Can I use an ORM like Eloquent or Doctrine instead of raw PDO? A: Absolutely! ORMs (Object-Relational Mappers) sit on top of PDO and make querying much easier (e.g.,User::find(5)). For learning purposes, raw PDO is essential, but in production, ORMs are heavily utilized.
16. Summary
In Chapter 21, we brought our API to life by connecting it to MySQL using PDO. We learned how to configure PDO to return associative arrays for perfect JSON encoding, how to safely insert JSON payloads into the database using prepared statements to prevent SQL injection, and how to structure our queries securely.17. Next Chapter Recommendation
We can now handle text and numbers perfectly. But what if a user wants to upload a profile picture? Proceed to Chapter 22: File Upload APIs to learn how to handlemultipart/form-data and securely store files on your server.