MySQL with PHP
Learn how to connect a PHP application to MySQL using PDO, run queries, fetch results, and safely insert user input with prepared statements.
Introduction
Everything you have learned so far has been run through a MySQL client or MySQL Workbench. In real applications, though, queries are almost always sent from application code — a web server processing requests from users. PHP and MySQL are one of the most common pairings in web development, powering huge platforms like WordPress.
This lesson shows you how to connect to MySQL from PHP using PDO (PHP Data Objects), MySQL's most widely recommended PHP interface, and how to safely pass user input into your queries.
- How to connect to MySQL from PHP using PDO.
- How to run a query and fetch results as an associative array.
- How to use a prepared statement to safely insert user input.
- How this maps onto PrograMinds's own PHP course, if you have taken it.
Connecting with PDO
PDO gives PHP a consistent way to talk to several different database systems, MySQL included. To connect, you create a new PDO instance with a connection string (called a DSN), your username, and your password.
<?php
$host = 'localhost';
$db = 'school';
$user = 'school_app';
$pass = 'Str0ng!AppPass_2026';
try {
$pdo = new PDO(
"mysql:host=$host;dbname=$db;charset=utf8mb4",
$user,
$pass
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully.";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION means PDO throws a catchable exception on error instead of silently failing, which makes problems far easier to notice and debug.
Running Queries and Fetching Results
Once connected, you can run a query with query() and read the rows back one at a time with fetch(), or all at once with fetchAll(). Passing PDO::FETCH_ASSOC returns each row as an associative array keyed by column name, which is the most convenient form to work with.
<?php
$stmt = $pdo->query('SELECT id, name, marks FROM students');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'] . ' scored ' . $row['marks'] . "\n";
}Alex scored 78
Sam scored 65
Priya scored 91Prepared Statements with PHP
Just as covered in the Security Best Practices lesson, any value coming from a user — a form submission, a URL parameter — should never be concatenated directly into a SQL string. PDO's prepare() and execute() make this simple: write the query once with placeholders, then pass the real values in separately.
<?php
$name = $_POST['name'];
$marks = $_POST['marks'];
$stmt = $pdo->prepare(
'INSERT INTO students (name, marks) VALUES (?, ?)'
);
$stmt->execute([$name, $marks]);
echo "Student added with ID: " . $pdo->lastInsertId();Student added with ID: 4Never build a query like "INSERT INTO students (name) VALUES ('" . $name . "')". Always use a prepared statement with placeholders (?), exactly as shown above, whenever a value originates from user input.
If You Have Taken the PHP Course
If you have already taken PrograMinds's PHP course, this will feel familiar — the dedicated PDO lesson there covers connecting to MySQL, running queries, and prepared statements in exactly the same way shown here, just from the PHP side rather than the MySQL side. The two lessons are meant to reinforce each other, so feel free to cross-reference it if any of these examples need a refresher on PHP syntax itself.
Common Mistakes
- Concatenating $_POST or $_GET values directly into a SQL string instead of using a prepared statement.
- Forgetting to set PDO::ATTR_ERRMODE, causing failures to go unnoticed.
- Hardcoding database credentials directly in a script instead of loading them from a safer configuration source.
- Forgetting that fetch() returns one row per call, and needs a loop to read multiple rows.
Key Takeaways
- PDO provides a consistent way to connect PHP to MySQL and other databases.
- query() combined with fetch(PDO::FETCH_ASSOC) reads rows back as associative arrays.
- prepare() and execute() with placeholders safely handle user-supplied values.
- This mirrors the PDO lesson in PrograMinds's PHP course, so the two can reinforce each other.
Summary
PDO is the standard, safe way to connect PHP applications to MySQL. Connecting is a few lines of setup, reading results is a simple loop, and prepared statements keep every piece of user input completely safe from SQL injection.
In this lesson, you learned to connect to MySQL from PHP, run and fetch queries, and safely insert data with prepared statements. Next, you will see how the same ideas translate to Java using JDBC.
- You can connect to MySQL from PHP using PDO.
- You can run a query and fetch results as associative arrays.
- You can safely insert user input using a prepared statement.
- You are ready to connect MySQL to Java using JDBC.