PHP MySQL Database Connection
# Chapter 21: PHP MySQL Database Connection
1. Introduction
Welcome to Chapter 21! While text files are okay for simple logs, real web applications require robust, searchable, and highly organized data storage. Enter the Database. MySQL is the most popular open-source relational database management system, and it works seamlessly with PHP. In this chapter, we will learn what MySQL is, how to interact with it using phpMyAdmin, and the two primary ways PHP connects to a database:mysqli and PDO.
2. Learning Objectives
By the end of this chapter, you will be able to:- Understand basic relational database concepts.
- Navigate phpMyAdmin to create a database.
-
Connect to MySQL using the
mysqliprocedural method.
-
Connect to MySQL using the modern
PDOobject-oriented method.
- Handle database connection errors gracefully.
3. MySQL Basics and phpMyAdmin
MySQL stores data in Tables, which consist of Rows and Columns (just like a spreadsheet). If you installed XAMPP or WAMP, you already have MySQL installed! To manage it easily without using a command line, XAMPP includes phpMyAdmin, a visual interface for databases.- 1. Open your XAMPP Control Panel.
- 2. Start both Apache and MySQL.
-
3.
Click the Admin button next to MySQL (or go to
http://localhost/phpmyadminin your browser).
-
4.
Click New on the left sidebar, name your database
php_course, and click Create.
4. PHP Database Extensions: mysqli vs PDO
PHP does not talk to MySQL automatically. It needs a driver/extension. You have two choices:- MySQLi (MySQL Improved): Designed specifically for MySQL databases. It has both procedural and object-oriented syntax. It is slightly faster but only works with MySQL.
- PDO (PHP Data Objects): A robust, modern, purely object-oriented extension. The biggest advantage of PDO is that it works with over 12 different database systems (MySQL, PostgreSQL, SQLite). If you switch databases later, you don't have to rewrite your entire codebase.
*Industry Standard:* PDO is highly recommended for modern development. We will show both, but focus on PDO.
5. Connecting with MySQLi (Object-Oriented)
To connect, you need 4 pieces of information: Servername, Username, Password, and Database Name. On XAMPP, the default username is alwaysroot, and the password is "" (empty).
6. Connecting with PDO
PDO requires a Data Source Name (DSN) string, which dictates the host and database. It also uses atry/catch block for elegant error handling (which we will cover fully in Chapter 26).
7. Real-World Examples
In a real application, you NEVER put your database connection code directly intoindex.php. If you do, you have to rewrite the credentials on every single page that needs database access. Instead, create a dedicated config.php file containing the PDO connection, and require_once 'config.php'; at the top of any file that needs to talk to the database.
8. Output Explanations
When the PDO script runs, PHP attempts to reachlocalhost using root and no password. If MySQL is running in XAMPP, the connection is established, and the PDO object is stored in the $pdo variable. The message "Connected successfully" echoes. If you turn off MySQL in XAMPP and refresh, the catch block intercepts the crash, preventing a fatal script error, and echoes the specific MySQL error message instead.
9. Common Mistakes
-
Wrong Credentials on Live Servers: Beginners often upload their
config.phpto Hostinger or cPanel and wonder why it breaks. Your live server does NOT userootwith an empty password. You must create a user in your cPanel MySQL databases tab and update the script.
- Forgetting to start MySQL: If XAMPP Apache is running but MySQL is stopped, the connection will time out and fail.
-
Leaking Credentials: Uploading
config.phpto a public GitHub repository. Hackers scan GitHub for these files to steal database access. Always use.gitignoreor.envfiles for credentials.
10. Best Practices
- Use PDO. The object-oriented syntax is cleaner, and switching database engines in the future requires minimal changes.
-
Wrap PDO connections in
try/catchblocks so you can display a friendly "Website Under Maintenance" page to users if the database goes down, rather than exposing raw MySQL errors.
11. Exercises
-
1.
Open phpMyAdmin and manually create a database named
test_db.
-
2.
Write a
config.phpfile using PDO to connect totest_db.
-
3.
Force an error by changing the username to
wrong_userand observe the catch block output.
12. Mini Project: Reusable Database Connection
Task: Create an organized, reusable database connection file that handles errors gracefully.db.php
index.php
13. Coding Challenges
Challenge 1: Write a MySQLi connection script, but use the procedural syntax (mysqli_connect()) instead of the object-oriented syntax. (You will need to search the PHP documentation for this!)
14. MCQs with Answers
1. What is phpMyAdmin used for? A) It is the database server itself. B) A visual interface for managing MySQL databases via a web browser. C) A PHP compiler. D) A tool to write HTML faster. *Answer: B*2. Why is PDO generally preferred over MySQLi? A) PDO is the only one that works on Windows. B) PDO supports multiple different database systems, whereas MySQLi only supports MySQL. C) PDO does not require a password. D) PDO uses less server memory. *Answer: B*
3. What does die() do in a connection error block?
A) Deletes the database.
B) Prints a message and immediately terminates the execution of the PHP script.
C) Kills the MySQL server.
D) Pauses the script for 5 seconds.
*Answer: B*
15. Interview Questions
Q: What is a DSN? *A:* DSN stands for Data Source Name. It is a string used by PDO to describe the database connection. It specifies the database driver (likemysql:), the host (localhost), and the database name (dbname=my_db).
Q: Why is charset=utf8mb4 important in your DSN?
*A:* While standard utf8 in MySQL only supports 3-byte characters, utf8mb4 fully supports 4-byte characters. This is absolutely required if you want your database to safely store and retrieve modern Emojis or complex international characters without data truncation.
16. FAQs
Q: Do I need to manually close the PDO connection at the end of the file? *A:* No. PHP automatically destroys the connection when the script finishes executing. If you urgently need to close it early to save memory, you can set$pdo = null;.
17. Summary
The bridge between your code and permanent storage has been built! You learned what MySQL is, navigated phpMyAdmin, and wrote professional, robust connection scripts using both MySQLi and the modern PDO standard. You also learned how to usetry/catch to gracefully handle offline databases.
18. Next Chapter Recommendation
Now that we have a$pdo object connected to MySQL, what do we do with it? In Chapter 22: PHP CRUD Operations, we will learn how to Create, Read, Update, and Delete data directly from the database using PHP!