Connecting PHP to MySQL
A database connection allows PHP to send SQL to MySQL and receive results. Keep the connection in one reusable file.
Create the connection file
Create includes/db.php:
<?php
$host = "localhost";
$dbname = "campready_db";
$username = "root";
$password = "";
$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
try {
$pdo = new PDO($dsn, $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
} catch (PDOException $error) {
exit("Database connection unavailable.");
}
XAMPP often uses an empty local root password, but never assume this on a hosted server. Do not reveal connection details or raw errors to users.
Use the connection
<?php
require __DIR__ . "/includes/db.php";
$stmt = $pdo->query("SELECT activity_id, activity_name FROM activities");
$activities = $stmt->fetchAll();
Why these choices matter
utf8mb4supports a broad range of characters.- exceptions make failures detectable.
- associative results give meaningful field names.
- a shared file avoids repeated credentials.
- the generic user message avoids exposing server details.
Check
- The connection file is reused.
- The database name is correct.
- The page works while MySQL is running.
- A stopped database produces a safe message.
- Credentials are excluded from screenshots and public repositories.