Connecting to a MySQL Database
Use PHP to connect to a MySQL database.
Connecting to a MySQL Database is a free PHP Academy lesson on CoddyKit — lesson 2 of 6. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 6 lessons in the course, and your progress syncs across the web and the CoddyKit app.
1
Connecting to a MySQL Database
Welcome to the next lesson! In this lesson, you’ll learn how to connect PHP to a MySQL database. This is a crucial step for creating dynamic, data-driven web applications. Let’s get started!

2
Why Connect to a Database?
Connecting to a database allows your PHP scripts to:
- Store and retrieve user data.
- Display dynamic content based on database queries.
- Save application settings and logs.
Key Point: A database connection bridges your application and the stored data.
3
Requirements for Connecting to a Database
Before connecting, ensure you have:
- A MySQL database installed and running.
- Database credentials (hostname, username, password, and database name).
- PHP extensions for database connections (PDO or MySQLi).
Tip: Use PDO for database-agnostic connections.
4
Connecting Using PDO
PDO (PHP Data Objects) is a flexible, object-oriented approach to database connections. Example:
Explanation:
$dsn: Data Source Name, specifies the database type, host, and name.$usernameand$password: Credentials to access the database.setAttribute(): Configures connection options (e.g., error handling).
<?php
$dsn = "mysql:host=localhost;dbname=testdb";
$username = "root";
$password = "";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
5
Connecting Using MySQLi
MySQLi is a MySQL-specific extension for database connections. Example:
Tip: Use MySQLi for simpler projects that only require MySQL.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
?>
6
Handling Connection Errors
Always handle connection errors gracefully to improve user experience. Example:
Key Point: Avoid displaying detailed error messages to users.
<?php
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
error_log("Database connection error: " . $e->getMessage());
echo "Sorry, something went wrong. Please try again later.";
}
?>7
Best Practices for Database Connections
Follow these best practices:
- Store database credentials in a secure, configuration file.
- Use environment variables for sensitive information.
- Close the connection when it’s no longer needed.
Example:
<?php
$pdo = null; // Closes the PDO connection
?>
8
Checking the Database Connection
After setting up the connection, ensure it works by running a simple query. Example:
Tip: Use this query to confirm the connection is successful.
<?php
$stmt = $pdo->query("SELECT DATABASE()");
$result = $stmt->fetchColumn();
echo "Connected to the database: $result";
?>
9
10
Great Job!
Congratulations! You’ve successfully learned how to connect PHP to a MySQL database using PDO and MySQLi. In the next lesson, we’ll explore how to create and populate tables in a database. Let’s keep coding!

Frequently asked questions
Is the “Connecting to a MySQL Database” lesson free?
Yes — the full text of “Connecting to a MySQL Database” is free to read here on the web, and the PHP Academy course includes 6 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Connecting to a MySQL Database”?
Use PHP to connect to a MySQL database. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 6, so you can start here or from the beginning and move at your own pace.
How long does the “Connecting to a MySQL Database” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Introduction to Databases
- Connecting to a MySQL Database
- Managing Tables
- Performing CRUD Operations
- Prepared Statements
- Working with PDO