Database

Rhapsody provides a lightweight PDO wrapper with support for multiple database drivers and query logging for debugging.

Configuration

Configure your database connection in the .env file:

DB_HOST=localhost
DB_PORT=3306
DB_NAME=your_database
DB_USER=your_username
DB_PASS=your_password
DB_DRIVER="mysql" # mysql, pgsql, sqlite, or sqlsrv

Supported Drivers

  • MySQL – Default driver
  • PostgreSQL (pgsql)
  • SQLite – Use :memory: for in-memory testing
  • SQL Server (sqlsrv)

Using the Database

The Database class is a singleton that lazily connects to the database on first use. This means pages that don't need the database won't open a connection.

Pro tip: It is best practice to place database queries inside models, rather than in your controllers (separation of concerns). This will keep your controllers clutter-free and make testing / maintaining your code much simpler. See models documentation for more information.

Getting a Connection

use Rhapsody\Core\Database;

// Get the global instance
$db = Database::getInstance($config);
$pdo = $db->getConnection();

// Execute a query
$stmt = $pdo->query("SELECT * FROM users WHERE id = 1");
$user = $stmt->fetch();

Prepared Statements

$pdo = Database::getInstance($config)->getConnection();
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => 'user@example.com']);
$user = $stmt->fetch();

Query Logging

The TraceablePDO class extends the native PDO and logs all queries for debugging purposes. The debug toolbar displays these logs in the Database panel.

To access the query log programmatically:

$queries = TraceablePDO::getQueryLog();
foreach ($queries as $query) {
    echo $query['sql'] . ' (' . $query['executionMS'] . 'ms)';
}

N+1 Query Detection

The debug toolbar automatically detects and warns about N+1 query patterns when the same query is executed multiple times.