CHAPTER 07
Beginner
Working with MySQL Databases
Updated: May 14, 2026
20 min read
# CHAPTER 7
Working with MySQL Databases
1. Introduction
Variables and arrays are temporary; when the PHP script finishes running, the data is erased. For a web application to be useful, it must permanently store user accounts, blog posts, and products. This is where the Database comes in. In this chapter, we will connect our PHP scripts to a MySQL database using the modern, secure PDO (PHP Data Objects) method.2. Learning Objectives
By the end of this chapter, you will be able to:- Understand the role of SQL and MySQL in web development.
- Establish a secure database connection using PDO.
-
Handle database connection errors gracefully using
try...catch.
- Run basic queries to fetch data.
3. Beginner-Friendly Explanation
Imagine a massive library. The MySQL Database is the library building. The Tables inside the database are the filing cabinets (one for Users, one for Books). SQL (Structured Query Language) is the language the librarian speaks. If PHP wants to know the password of a user, PHP must write a note in SQL (SELECT password FROM users WHERE name = 'John') and hand it to the MySQL Database. The database reads the note, opens the filing cabinet, grabs the password, and hands it back to PHP.
4. What is PDO?
Historically, developers usedmysqliconnect() to talk to databases. Today, the industry standard is PDO (PHP Data Objects).
*Why?* Because PDO provides an incredibly secure feature called Prepared Statements (which stops hackers from destroying your database), and it works with 12 different types of databases (MySQL, PostgreSQL, SQLite), meaning you can switch databases without rewriting all your PHP code.
5. Step 1: Create the Database (in phpMyAdmin)
Before writing PHP, you must create a database.-
1.
Open XAMPP and go to
http://localhost/phpmyadmin.
-
2.
Click "New" and create a database named
appdb.
-
3.
Create a table named
userswith three columns:
-
id(INT, Primary Key, Auto Increment)
-
name(VARCHAR 100)
-
email(VARCHAR 150)
6. Step 2: Connecting PHP to MySQL
We will create a dedicated file calleddb.php that handles the connection. We use a try...catch block. If the connection fails, it "catches" the error instead of crashing the whole website.
db.php
php
7. Step 3: Fetching Data (A Basic Query)
Now that we are connected, let's fetch some data from theusers table.
index.php
php
8. The Separation of Concerns
Notice that we createddb.php as a separate file, and used require 'db.php'; inside index.php.
If you have 50 different pages on your website that need database access, you don't want to type the database password 50 times. By putting it in one file, you can just require it everywhere. If your password changes, you only update it in one file.
9. Best Practices
-
Keep Passwords Secure: In a production environment, you never hard-code passwords directly into
db.php. You use Environment Variables (e.g., a.envfile) so that if a hacker steals your code files, they still don't get the database password.
10. Common Mistakes
-
Leaking Errors to the Public: The
catch (PDOException $e)block prints the exact reason the database failed. This is great for your local computer, but on a live website, printing$e->getMessage()might reveal your database username to a hacker. On live sites, you just print: "A server error occurred."
11. Exercises
-
1.
Explain the purpose of a
try...catchblock when connecting to a database.
12. Coding Challenges
-
Challenge: Use phpMyAdmin to insert 3 fake users into your
userstable. Then, modify the PHP script toechoonly the names of the users, wrapped in HTML<h1>tags.
13. MCQs with Answers
Question 1
What is the modern, secure, and flexible standard in PHP for connecting to a database?
Question 2
Why do developers place the database connection code in a separate file (e.g., db.php) and require it in other files?
14. Interview Questions
-
Q: Explain the advantages of using PDO over the older
mysqli*functions.
- Q: How do you securely handle a failed database connection in PHP so it doesn't crash the entire web application ungracefully?
15. FAQs
Q: Can I use MongoDB instead of MySQL with PHP? A: Yes! While PHP and MySQL are the classic "LAMP" stack pairing, PHP has drivers for NoSQL databases like MongoDB. However, PDO is specifically designed for relational SQL databases.16. Summary
In Chapter 7, we achieved permanence. We learned that the MySQL Database is the permanent filing cabinet for our web application. By utilizing the modern PDO extension, we established a secure bridge between our PHP logic and the MySQL data. By separating our connection credentials into a reusabledb.php file, we set the foundation for building scalable, professional applications.