Skip to main content
phpMyAdmin Guide
CHAPTER 17 Beginner

How to Connect PHP to MySQL | mysqli & PDO Guide

Updated: May 16, 2026
15 min read

# 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 mysqli vs PDO extensions.
  • 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. 1. mysqli (MySQL Improved): This extension *only* works with MySQL databases. It is slightly easier for absolute beginners to learn.
  1. 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 named db_connect.php in your XAMPP htdocs folder.
php
1234567891011121314151617
<?php
// 1. Define the connection credentials
$host = "localhost";
$username = "root";       // Your XAMPP user
$password = "";           // Blank by default in XAMPP
$database = "company_db"; // The DB you created in phpMyAdmin

// 2. Attempt the connection using mysqli
$conn = mysqli_connect($host, $username, $password, $database);

// 3. Check if the connection failed
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully to the database!";
?>

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.
php
123456789101112131415
<?php
require &#039;db_connect.php'; // Pulls in the connection we just wrote

$sql = "SELECT id, username, email FROM users";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // Loop through the results and print them
    while($row = mysqli_fetch_assoc($result)) {
        echo "ID: " . $row["id"]. " - Name: " . $row["username"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 results found.";
}
?>

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):
php
12
$user_email = $_POST[&#039;email']; // Data from a form
$sql = "SELECT * FROM users WHERE email = &#039;$user_email'";

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

php
1234567891011121314151617
<?php
$user_email = "alice@example.com"; // Imagine this came from a form

// 1. Prepare the SQL statement with a ? placeholder
$stmt = $conn->prepare("SELECT username FROM users WHERE email = ?");

// 2. Bind the actual data to the placeholder ("s" means String)
$stmt->bind_param("s", $user_email);

// 3. Execute the secure query
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    echo $row[&#039;username'];
}
?>

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. 1. HTML Form sends $POST['username'] and $POST['password'].
  1. 2. dbconnect.php establishes the connection.
  1. 3. PHP hashes the password: $hashedpw = passwordhash($POST['password'], PASSWORDDEFAULT);
  1. 4. PHP executes a Prepared Statement:
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)"); $stmt->bind
param("ss", $POST['username'], $hashedpw);
  1. 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.php and then upload that file to a public GitHub repository. Hackers scan GitHub for the word "mysqliconnect" and steal passwords daily. Use .env environment 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. 1. What is the fundamental difference in database compatibility between the mysqli extension and the PDO extension?
  1. 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

Question 1

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?

Question 2

What is the explicit mechanical purpose of a "Prepared Statement" in PHP/MySQL integration?

14. Interview Questions

  • Q: Compare and contrast the mysqli and PDO extensions 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 your db_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!

16. Summary

You are now a Full Stack Developer. By writing secure connection scripts, extracting data via loops, and ruthlessly implementing Prepared Statements to annihilate SQL injection vulnerabilities, you have successfully linked your frontend web application to your backend database architecture.

17. Next Chapter Recommendation

We know how to connect and perform basic reads and inserts. In Chapter 18: Building CRUD Applications with phpMyAdmin and PHP, we will synthesize everything to build a complete, functional Web Application with Create, Read, Update, and Delete capabilities.

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