CHAPTER 26
Beginner
Connecting MySQL with PHP
Updated: May 16, 2026
6 min read
# CHAPTER 26
Connecting MySQL with PHP
1. Introduction
Typing raw SQL commands into the MySQL terminal is great for learning, but users don't interact with terminals—they interact with Web Browsers. To bridge the gap between a user clicking a button in Chrome and data being saved in MySQL, we need a backend language. PHP was practically built to run alongside MySQL (the 'P' and 'M' in XAMPP!). In this chapter, we transition from pure Database Administration to Backend Web Development, establishing a secure, programmatic connection to our database.2. Learning Objectives
By the end of this chapter, you will be able to:-
Differentiate between the
mysqliandPDOextensions.
- Establish a secure database connection using PDO.
- Handle connection errors gracefully using Try-Catch blocks.
- Execute basic queries from PHP.
- Architect parameterized Prepared Statements to prevent SQL Injection.
3. The mysqli vs. PDO Debate
PHP offers two different tools (extensions) to talk to MySQL:
-
1.
mysqli(MySQL Improved): Extremely fast, but it ONLY works with MySQL. If your company ever switches to PostgreSQL, you have to rewrite your entire codebase.
-
2.
PDO(PHP Data Objects): The modern industry standard. It supports 12 different database engines using the exact same code syntax. It is highly secure and object-oriented. We will use PDO.
4. Establishing the Connection
To connect, PHP needs the server address, the database name, the username, and the password. We wrap the connection attempt in atry-catch block so the website doesn't crash catastrophically if the database is offline.
php
5. Executing a Simple Query
Once connected, we can ask the$pdo object to execute SQL commands and return the data as PHP Arrays!
php
6. The Danger of User Input
What if we want to search for a specific user based on an email address typed into an HTML form? If you do this, you will be fired:$sql = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'";
*As learned in Chapter 25, this invites an immediate SQL Injection attack.*
7. The Solution: Prepared Statements
Instead of concatenating raw user input into the SQL string, we place a question mark? or a named placeholder :email exactly where the data should go.
php
8. Common Mistakes
-
Exposing Database Credentials: Beginners often type
$password = 'secret123'directly into a public GitHub repository. Hackers scan GitHub 24/7 for exposed passwords. You must store credentials in an external, hidden.envfile!
-
Not using
htmlspecialchars: While Prepared Statements prevent SQL Injection (hacking the database), if you print user-submitted data to the screen without wrapping it inhtmlspecialchars(), you expose yourself to XSS (Cross-Site Scripting) attacks, which hacks the user's browser!
9. Best Practices
-
Singleton Pattern: Never write the PDO connection code inside every single PHP file. Write it once inside a
database.phpfile, and simplyrequire 'database.php';at the top of any script that needs database access.
10. Exercises
- 1. What does the acronym PDO stand for in PHP?
-
2.
Rewrite the following insecure PHP query using a safe PDO Prepared Statement with a named placeholder
:username:
$pdo->query("SELECT * FROM users WHERE username = '$input'");
11. MCQ Quiz with Answers
Question 1
Why is PDO (PHP Data Objects) generally preferred over the mysqli extension in modern PHP development?
Question 2
When a PHP script needs to insert data submitted from an HTML form into the database, what technique MUST be used to prevent SQL Injection?
12. Interview Questions
-
Q: Detail the mechanical process of how a PDO Prepared Statement neutralizes a SQL Injection attack when a malicious string like
' OR 1=1 --is passed to it.
-
Q: Explain why database connection code in PHP should be wrapped inside a
try/catchblock. What are the consequences of failing to do so if the database server goes offline?
13. FAQs
Q: Does Node.js or Python use PDO? A: No, PDO is specific to PHP. However, every modern backend language has an equivalent library (e.g.,mysql2 in Node.js, psycopg2 in Python) that supports the exact same concept of secure Prepared Statements!