Skip to main content
PHP Backend Development Tutorial
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 used mysqliconnect() 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. 1. Open XAMPP and go to http://localhost/phpmyadmin.
  1. 2. Click "New" and create a database named appdb.
  1. 3. Create a table named users with 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 called db.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
1234567891011121314151617181920212223
<?php
// Database Credentials for local XAMPP
$host = &#039;localhost';
$dbname = &#039;app_db';
$user = &#039;root';       // Default XAMPP username
$pass = &#039;';           // Default XAMPP password is empty

try {
    // Create the PDO connection string (DSN)
    $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
    
    // Instantiate the PDO object
    $pdo = new PDO($dsn, $user, $pass);
    
    // Set PDO to throw an Exception if there is an SQL error
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "Database connected successfully!";
} catch (PDOException $e) {
    // If it fails, catch the error and stop the script
    die("Database connection failed: " . $e->getMessage());
}
?>

7. Step 3: Fetching Data (A Basic Query)

Now that we are connected, let's fetch some data from the users table.

index.php

php
123456789101112131415161718192021
<?php
// Include the database connection file
require &#039;db.php';

// Write the SQL note
$sql = "SELECT id, name, email FROM users";

// Ask PDO to run the query
$stmt = $pdo->query($sql);

// Fetch all the rows and format them as an Associative Array
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through the array and display the data in HTML
echo "<h2>Registered Users</h2>";
echo "<ul>";
foreach ($users as $user) {
    echo "<li>" . $user[&#039;name'] . " (" . $user['email'] . ")</li>";
}
echo "</ul>";
?>

8. The Separation of Concerns

Notice that we created db.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 .env file) 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. 1. Explain the purpose of a try...catch block when connecting to a database.

12. Coding Challenges

  • Challenge: Use phpMyAdmin to insert 3 fake users into your users table. Then, modify the PHP script to echo only 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 reusable db.php file, we set the foundation for building scalable, professional applications.

17. Next Chapter Recommendation

We know how to connect and fetch data, but how do we add, edit, and delete data securely? Proceed to Chapter 8: Building CRUD Applications in PHP.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·