Lesson 16 of 20

Working with MySQL

Connecting to MySQL

PHP provides the MySQLi and PDO extensions for database access. MySQLi is MySQL-specific; PDO supports multiple databases.

Example
<?php
// MySQLi connection
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'myapp';

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}
echo 'Connected successfully!';

// Query
$result = $conn->query('SELECT * FROM users');
while ($row = $result->fetch_assoc()) {
    echo $row['name'] . ' - ' . $row['email'] . "\n";
}

// Prepared statement (prevents SQL injection)
$stmt = $conn->prepare('SELECT * FROM users WHERE id = ?');
$stmt->bind_param('i', $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

$conn->close();
?>