PHP & MySQL Database Connection

May 29, 2025 1,561 views 1 min read
Beginner Tutorial
Tutorial Navigation

PHP & MySQL Database Connection

Connecting to a database is fundamental in PHP development. Here's how to do it securely:

<?php
try {
    $pdo = new PDO(
        "mysql:host=localhost;dbname=mysite",
        $username,
        $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
    
    // Prepare and execute query
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    echo "Welcome " . htmlspecialchars($user['name']);
    
} catch(PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    echo "Connection failed";
}
?>

Security Best Practices:

  • Use prepared statements
  • Validate and sanitize input
  • Handle errors properly
  • Use htmlspecialchars() for output
Try It Yourself

Practice what you've learned with our interactive code editor. Modify the code and see the results instantly!