PHP MySQL Connection with PDO
In this lesson: Connect PHP to MySQL with PDO, handle errors and run prepared queries safely — copy-paste code for XAMPP and live hosting. Connect now.
Connecting PHP to MySQL
Most real websites store data in a database. MySQL is the most common database used with PHP. To use it, PHP first connects to the database, then sends SQL queries to read or write data. The modern, safe way to do this in PHP is with PDO and prepared statements.
Make a connection (PDO)
<?php
try {
$pdo = new PDO(
"mysql:host=localhost;dbname=school",
"root", // username
"" // password
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected!";
} catch (PDOException $e) {
echo "Failed: " . $e->getMessage();
}
?>
The connection string names the host and database. The try-catch catches problems (like a wrong password) so your page does not crash with a raw error.
Insert data safely
Use a prepared statement with placeholders, then pass the values separately.
<?php
$sql = "INSERT INTO students (name, marks) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute(["Aman", 88]);
echo "Row added";
?>
The ? marks are placeholders. The real values ("Aman", 88) go in execute(), so they can never be mistaken for SQL — this stops SQL injection.
Fetch data
<?php
$stmt = $pdo->query("SELECT name, marks FROM students");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $r) {
echo $r["name"] . ": " . $r["marks"] . "\n";
}
?>
fetchAll(PDO::FETCH_ASSOC) returns every row as an associative array, so you read columns by name like $r["name"].
Why prepared statements
Never paste user input straight into SQL like this:
<?php
// DANGEROUS - do not do this:
$sql = "SELECT * FROM users WHERE name = '$name'";
?>
If $name contains SQL, an attacker can read or delete your data (SQL injection). Prepared statements keep the values separate from the query, which closes this hole completely.
Common mistakes
- Building SQL by pasting input. Always use placeholders and
execute(). - No try-catch. Connection or query errors then crash the page with raw messages.
- Wrong host or database name. Double-check the connection string details.
- Forgetting FETCH_ASSOC. Set it to read rows cleanly by column name.
Summary
- Connect PHP to MySQL with PDO, inside a try-catch.
- Use prepared statements with
?placeholders for all user data. - Pass real values in
execute()— never paste them into SQL. - Read results with
fetch()orfetchAll(PDO::FETCH_ASSOC). - Prepared statements are your main defence against SQL injection.
Next, understand the choice in PDO vs MySQLi, or build full data operations with PHP CRUD.
Frequently Asked Questions
How do I connect PHP to a MySQL database?
new PDO("mysql:host=localhost;dbname=school", "root", ""). Wrap it in a try-catch to handle connection errors cleanly.What is the difference between PDO and MySQLi?
What is a prepared statement and why use it?
How do I get results from a SELECT query?
fetch() for one row or fetchAll() for all rows. With PDO's FETCH_ASSOC mode you get each row as an associative array keyed by column name.