Skip to main content
Unlisted page
This page is unlisted. Search engines will not index it, and only users having a direct link can access it.

PHP MySQL Connection

Using MySQLi (Object-Oriented)

$conn = new mysqli("localhost", "username", "password", "database");

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

Using PDO

try {
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}

Best Practices

  • Always use prepared statements for SQL queries
  • Close connections when done: $conn->close() or $pdo = null
  • Store credentials in environment variables, not in code