PHP — MySQL Database
PDO connection
<?php
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=mydb;charset=utf8mb4',
'username',
'password',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
Querying
<?php
// SELECT
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll();
foreach ($users as $user) {
echo $user['name'] . "\n";
}
// Single row
$stmt = $pdo->query("SELECT * FROM users WHERE id = 1");
$user = $stmt->fetch();
?>
Prepared statements
<?php
// Insert
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(['Alice', 'alice@example.com']);
// Named parameters
$stmt = $pdo->prepare("SELECT * FROM users WHERE name = :name");
$stmt->execute(['name' => 'Alice']);
$user = $stmt->fetch();
// Update
$stmt = $pdo->prepare("UPDATE users SET email = :email WHERE id = :id");
$stmt->execute(['email' => 'new@example.com', 'id' => 1]);
?>
Transactions
<?php
try {
$pdo->beginTransaction();
$pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
$pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
echo "Transaction failed: " . $e->getMessage();
}
?>
Error handling
<?php
try {
$stmt = $pdo->prepare("SELECT * FROM nonexistent");
$stmt->execute();
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
Mini Practice
Write PHP code that:
- Connects to a database with PDO
- Uses prepared statements for INSERT
- Executes a transaction
- Handles database errors
Up Next
Congratulations! You've completed the PHP fundamentals. Continue exploring advanced topics like Composer, MVC, and frameworks.
Related Topics
Frequently Asked Questions about MySQL Database
What is MySQL Database in PHP?
MySQL Database is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn MySQL Database?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn MySQL Database.
Why is MySQL Database important in PHP?
MySQL Database is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.