EasyDB Documentation

repository·master·Indexed 20 days ago

https://github.com/paragonie/easydb

A simple database abstraction layer for PHP designed as a secure alternative to raw PDO usage. EasyDB focuses on separating data from instructions to prevent SQL injection, providing a concise API for common operations such as insert, update, delete, and fetching rows or cells. It includes features like EasyStatement for building complex dynamic WHERE clauses, EasyPlaceholder for handling SQL functions and IN clauses, and tryFlatTransaction for atomic database operations.

Tokens
7.5K
Snippets
37
Records
46
Agent score
73%

What's inside EasyDB

  1. Generate dynamic query conditions with EasyStatement

    master

    Use EasyStatement to build complex, dynamic WHERE clauses. It supports grouping conditions and special placeholders for IN clauses.

    // Basic dynamic conditions
    $statement = EasyStatement::open()
        ->with('last_login IS NOT NULL');
    
    if ($condition) {
        $statement->orWith('username LIKE ?', '%' . $db->escapeLikeValue($val) . '%');
    }
    
    // Using the statement in a query
    $user = $db->single("SELECT * FROM users WHERE $statement", $statement->values());
    
    // Handling IN clauses with ?*
    $roles = [1, 2];
    $statement = EasyStatement::open()->in('role IN (?*)', $roles);
    // Resulting SQL: role IN (?, ?)
    
    // Grouping conditions
    $statement = EasyStatement::open()
        ->group()
            ->with('subtotal > ?')
            ->andWith('taxes > ?')
        ->end()
        ->orGroup()
            ->with('cost > ?')
            ->andWith('cancelled = 1')
        ->end();
    // Resulting SQL: (subtotal > ? AND taxes > ?) OR (cost > ? AND cancelled = 1)
  2. Build SQL conditions with EasyStatement

    master

    The EasyStatement class provides a fluent interface for building complex SQL WHERE clauses safely. It allows you to chain conditions using logical AND and OR operators, handle nested groups, and manage parameter binding to prevent SQL injection.

    To start building a statement, use the static EasyStatement::open() method. You can then append conditions using andWith() (or its alias with()) and orWith(). To compile the statement into a raw SQL string for PDO, call sql() or cast the object to a string.

    use ParagonIE//EasyDB
    
    $statement = EasyStatement::open()
        ->andWith('status = ?', 'active')
        ->orWith('role = ?', 'admin');
    
    echo $statement->sql(); // "status = ? AND role = ?" (Note: actual logic depends on internal joiner state)
    // To get values for PDO execution:
    $params = $statement->values(); // ['active', 'admin']
  3. Create nested logical groups in EasyStatement

    master

    You can create nested logical groupings (e.g., WHERE (a = 1 OR b = 2) AND c = 3) using andGroup() and orGroup().

    • andGroup() starts a new sub-statement that will be joined to the parent with AND.
    • orGroup() starts a new sub-statement that will be joined to the parent with OR.
    • end() (or endGroup()) exits the current group and returns the context to the parent statement.

    If you call end() when there is no active group, a RuntimeException is thrown.

    $statement = EasyStatement::open()
        ->andWith('active = ?', 1)
        ->andGroup()
            ->orWith('type = ?', 'A')
            ->orWith('type = ?', 'B')
        ->end();
    
    echo $statement->sql(); // "active = ? AND (type = ? OR type = ?)"
  4. Initialize EasyDB with a PDO instance

    master

    To use EasyDB, instantiate the EasyDB class by passing an existing PDO instance. You can optionally specify the dbEngine (e.g., 'mysql', 'sqlite', 'pgsql', 'mssql') and an options array. If dbEngine is omitted, EasyDB will automatically detect it from the PDO driver name.

    Note: The constructor automatically sets PDO::ATTR_EMULATE_PREPARES to false and PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION to ensure security and proper error handling.

    $pdo = new PDO('sqlite:./database.db');
    $db = new EasyDB($pdo); // Engine detected automatically
    // OR
    $db = new EasyDB($pdo, 'mysql', [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);
  5. Perform a database transaction

    master

    Use tryFlatTransaction() to execute a block of code within a transaction. The callback receives the EasyDB instance. The transaction will automatically commit if the callback returns successfully or roll back if an exception is thrown.

    $save = function (\EasyDB\EasyDB $db) use ($userData, $query) : int {
        $db->safeQuery($query, [$userData['userId']]);
        return \Some\Other\Package::CleanUpTable($db);
    };
    
    $returnedInt = $db->tryFlatTransaction($save);
  6. Fetch a single cell or value

    master

    Use cell() to fetch a single value (like a count or a specific column) from a single row. cell() is variadic. If you prefer passing an array of parameters, use single() instead.

    // Using cell() with variadic arguments
    $exists = $db->cell(
        "SELECT count(id) FROM users WHERE email = ? AND username = ?",
        $_POST['email'],
        $_POST['username']
    );
    
    // Using single() with an array of arguments
    $exists = $db->single(
        "SELECT count(id) FROM users WHERE email = ?",
        array($_POST['email'])
    );
  7. Initialize EasyDB using Factory::fromArray()

    master

    The easiest way to create an EasyDB instance is using \ParagonIE\EasyDB\Factory::fromArray(). You pass an array containing the PDO DSN, username, and password.

    $db = \ParagonIE\EasyDB\Factory::fromArray([
        'mysql:host=localhost;dbname=something',
        'username',
        'putastrongpasswordhere'
    ]);
  8. Use EasyPlaceholder for SQL functions and stored procedures

    master

    When using insert() or update(), you can use EasyPlaceholder to include SQL functions (like NOW()) or complex expressions that should not be treated as literal values to be escaped.

    use \ParagonIE\EasyDB\EasyPlaceholder;
    
    $db->insert('user_auth', [
        'user_id' => 1,
        'timestamp' => new EasyPlaceholder('NOW()'),
        'location' => new EasyPlaceholder(
            "ST_GeomFromText(CONCAT('POINT(', ?, ' ', ?, ')'))",
            50.4019514,
            39.0639
        )
    ]);
  9. Insert a row into a table

    master

    Use insert() to add a new row. Pass the table name and an associative array where keys are column names and values are the data to insert.

    $db->insert('comments', [
        'blogpostid' => $_POST['blogpost'],
        'userid' => $_SESSION['user'],
        'comment' => $_POST['body'],
        'parent' => isset($_POST['replyTo']) ? $_POST['replyTo'] : null
    ]);