Skip to main content
SQL Fundamentals
CHAPTER 27 Beginner

PHP to MySQL Database Connection | mysqli vs PDO Tutorial

Updated: May 16, 2026
15 min read

# CHAPTER 27

Connecting SQL Databases with PHP

1. Introduction

You have spent 26 chapters mastering SQL within a graphical interface like phpMyAdmin. But end-users don't use phpMyAdmin; they use web browsers. To bridge the gap between a user clicking a button on a website and the database executing an SQL query, we need a backend programming language. In this chapter, we will use PHP, the language that powers nearly 80% of the web, to establish a secure connection to our SQL database and execute queries programmatically.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the role of PHP as the intermediary layer.
  • Differentiate between the mysqli and PDO extensions.
  • Establish a database connection using credentials.
  • Handle connection errors securely.
  • Execute a basic SQL query from a PHP script.

3. The Architecture (Browser -> PHP -> SQL)

  1. 1. The User visits index.php in their browser.
  1. 2. The PHP script boots up on the server.
  1. 3. The PHP script securely logs into the SQL database using a username and password.
  1. 4. The PHP script sends a text string containing SQL (e.g., "SELECT * FROM users") to the database.
  1. 5. The database processes the SQL and hands the data back to PHP.
  1. 6. PHP converts the data into HTML and sends it to the user's browser.

4. mysqli vs PDO

PHP has two primary ways to connect to a database:
  • mysqli (MySQL Improved): Designed specifically and exclusively for MySQL databases. It is slightly faster but limits you to one database engine.
  • PDO (PHP Data Objects): The modern, universal standard. PDO can connect to MySQL, PostgreSQL, SQLite, and Microsoft SQL Server using the exact same PHP code.

*We will cover both, but PDO is the industry standard for modern enterprise applications.*

5. Connecting with mysqli (Procedural)

To connect, you need 4 pieces of information: Host, Username, Password, and Database Name.
php
1234567891011121314151617
<?php
// 1. Define the connection credentials
$host = "localhost";
$username = "root"; // Default XAMPP username
$password = "";     // Default XAMPP password is empty
$database = "school_system";

// 2. Establish the connection!
$conn = mysqli_connect($host, $username, $password, $database);

// 3. Check for catastrophic failure
if (!$conn) {
    die("Database Connection Failed: " . mysqli_connect_error());
}

echo "Successfully connected to the database using mysqli!";
?>

6. Connecting with PDO (Object-Oriented)

PDO uses a "Data Source Name" (DSN) string and try/catch blocks for robust error handling.
php
1234567891011121314151617181920212223
<?php
$host = &#039;localhost';
$db   = &#039;school_system';
$user = &#039;root';
$pass = &#039;';

// The DSN strictly defines the engine (mysql) and the charset
$dsn = "mysql:host=$host;dbname=$db;charset=utf8mb4";

try {
    // Attempt to instantiate the PDO connection object
    $pdo = new PDO($dsn, $user, $pass);
    
    // Set PDO to throw an Exception if a query fails
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "Successfully connected to the database using PDO!";
    
} catch (\PDOException $e) {
    // If the connection fails, catch the error so the website doesn't crash!
    die("Database Connection Failed: " . $e->getMessage());
}
?>

7. Executing a Simple Query (PDO)

Once connected, you can send SQL commands directly to the database.
php
1234567891011121314
<?php
// ... (PDO connection code from above) ...

// 1. Write the SQL string
$sql = "SELECT id, first_name FROM students LIMIT 5";

// 2. Query the database
$stmt = $pdo->query($sql);

// 3. Loop through the returned rows and format them for the browser!
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "Student ID: " . $row[&#039;id'] . " - Name: " . $row['first_name'] . "<br>";
}
?>

8. Common Mistakes

  • Hardcoding Credentials in Public Files: Beginners often put their database password directly inside index.php. If the PHP server crashes, the raw code might be displayed to the user, exposing the password! Passwords should always be stored in a separate, hidden .env file that PHP reads securely.
  • Suppressing Errors: Using @mysqliconnect() suppresses error messages. If the connection fails, you will get a blank white screen and have no idea why. Always handle connection errors properly!

9. Best Practices

  • Standardize on PDO: Unless you are maintaining a 15-year-old legacy codebase, you should always choose PDO. It supports Prepared Statements (Chapter 26) perfectly and allows you to switch from MySQL to PostgreSQL in the future by changing exactly one line of code (the DSN).

10. Exercises

  1. 1. What are the four specific credentials required to authenticate a connection to an SQL database?
  1. 2. What is the modern, universal PHP extension used to connect to almost any relational database engine?

11. SQL Challenges

Write the exact PHP variable $dsn string required for a PDO connection to a MySQL database running on localhost with the database name ecommerce
db and charset utf8mb4.
php
1
$dsn = "mysql:host=localhost;dbname=ecommerce_db;charset=utf8mb4";

12. MCQ Quiz with Answers

Question 1

What is the primary architectural advantage of using the PDO extension over the mysqli extension when connecting a PHP backend to a database?

Question 2

When establishing a database connection in PHP, what is the purpose of the try/catch block?

13. Interview Questions

  • Q: Explain the role of the backend server (PHP/Node.js) in a modern web architecture. Why doesn't the user's browser (JavaScript) simply connect directly to the SQL database? (Hint: Security and Credential exposure).
  • Q: Compare and contrast the mysqli and PDO extensions. Which would you choose for a new enterprise project and why?

14. FAQs

Q: I get "Access denied for user 'root'@'localhost'". Why? A: This means your connection code works perfectly, but you provided the wrong password or username! If you are using a standard XAMPP installation, the username is usually root and the password is an empty string "".

15. Summary

You have built the bridge. By defining your credentials, selecting the modern PDO extension, and handling connection exceptions gracefully, you have successfully linked your web application to your secure database vault, allowing the two systems to communicate seamlessly.

16. Next Chapter Recommendation

Our PHP script can connect to the database and run a simple SELECT query. But how do we build a real application? How do we securely INSERT data that a user types into a form? In Chapter 28: Building CRUD Applications with SQL, we will utilize Prepared Statements to build a complete, interactive web system.

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: ·