How to Connect PHP to MySQL | mysqli & PDO Guide
# CHAPTER 17
Connecting PHP Applications with MySQL
1. Introduction
phpMyAdmin is a fantastic graphical tool for database administrators, but your website's actual end-users will never see it. When a user fills out a "Contact Us" HTML form on your website and clicks Submit, it is the job of your backend programming language (PHP) to take that data, connect to MySQL, and insert it into the database. In this chapter, we will bridge the gap between your web application and your database engine by writing the connection code.2. Learning Objectives
By the end of this chapter, you will be able to:- Understand the PHP-to-MySQL connection flow.
-
Compare
mysqlivsPDOextensions.
- Write a secure database connection script.
- Execute basic SQL queries via PHP.
- Prevent SQL Injection using Prepared Statements.
3. The Two Extensions: mysqli vs PDO
PHP cannot talk to MySQL natively. It requires a translator (an extension).
-
1.
mysqli(MySQL Improved): This extension *only* works with MySQL databases. It is slightly easier for absolute beginners to learn.
- 2. PDO (PHP Data Objects): This is the industry standard. PDO works with 12 different database engines (MySQL, PostgreSQL, SQLite). If you build your app with PDO, and later decide to switch from MySQL to PostgreSQL, you don't have to rewrite all your code!
*Note: In this course, we will use mysqli for simplicity, but acknowledge PDO as the enterprise standard.*
4. Establishing the Connection
Create a file nameddb_connect.php in your XAMPP htdocs folder.
If you open http://localhost/db_connect.php in your browser and see the success message, your PHP app is officially talking to your database!
5. Executing a Simple Query (Read/SELECT)
Let's pull data out of our database and display it on the website.6. The Threat: SQL Injection
If you take user input from an HTML form and inject it directly into a SQL string, you will be hacked. BAD CODE (Vulnerable):If a hacker types ' OR 1=1 -- into the email box, the SQL statement becomes:
SELECT * FROM users WHERE email = '' OR 1=1 --'
Because 1 always equals 1, the database ignores the email check and logs the hacker into the first account it finds (usually the Admin)!
7. The Solution: Prepared Statements
To prevent SQL Injection mathematically, you must use Prepared Statements. Instead of mixing data with the SQL command, you send the SQL command first (with a placeholder?), and send the data separately later.
GOOD CODE (Secure):
Even if the user types malicious code, the database treats it strictly as a text string, not as an executable command!
8. Mini Project: The Registration Form
Scenario: Building the backend for a signup page.-
1.
HTML Form sends
$POST['username']and$POST['password'].
-
2.
dbconnect.phpestablishes the connection.
-
3.
PHP hashes the password:
$hashedpw = passwordhash($POST['password'], PASSWORDDEFAULT);
- 4. PHP executes a Prepared Statement:
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bindparam("ss", $POST['username'], $hashedpw);
- 5. The query executes. You can verify it worked by opening phpMyAdmin and checking the Browse tab!
9. Common Mistakes
-
Putting Credentials in Public Repositories: Never hardcode your actual production database password into
dbconnect.phpand then upload that file to a public GitHub repository. Hackers scan GitHub for the word "mysqliconnect" and steal passwords daily. Use.envenvironment variables to hide credentials!
10. Best Practices
-
Close the Connection: Although PHP automatically closes connections when the script ends, it is a professional best practice to explicitly close it yourself using
mysqliclose($conn);at the very bottom of your file to free up server RAM instantly.
11. Exercises
-
1.
What is the fundamental difference in database compatibility between the
mysqliextension and thePDOextension?
- 2. What hacking technique allows a malicious user to log in without a password by manipulating the raw SQL string?
12. Database Challenges
A junior developer writes this code:$sql = "DELETE FROM users WHERE username = '" . $POST['username'] . "'";. As the lead developer, you reject this code during review. Why? Rewrite it conceptually explaining the security requirement.
*(Answer: The code is vulnerable to severe SQL Injection because raw user input is concatenated directly into the SQL string. It must be rewritten using a Prepared Statement where the username is replaced with a ? parameter, forcing the database to evaluate the input strictly as data rather than an executable command).*
13. MCQ Quiz with Answers
When architecting the backend of a PHP web application, what is the primary architectural advantage of utilizing the PDO (PHP Data Objects) extension over the mysqli extension?
What is the explicit mechanical purpose of a "Prepared Statement" in PHP/MySQL integration?
14. Interview Questions
-
Q: Compare and contrast the
mysqliandPDOextensions in PHP. If you were architecting an enterprise SaaS application from scratch today, which would you choose and why?
-
Q: Explain the mechanics of an SQL Injection attack (
' OR 1=1 --). Detail the exact step-by-step workflow of how a Prepared Statement completely mitigates this vulnerability at the database engine level.
15. FAQs
Q: I uploaded my PHP code to my live web host, but it says "Access Denied". Why? A: Because yourdb_connect.php file still says $username = "root" and $password = ""! Remember Chapter 16? On a live shared host, you must update those variables to match the specific cPanel user and password you created!