Query builder

Use the query builder to describe a SQL statement in PHP. Query::select() starts a query for a table. Add the columns, conditions, sort order, and row limit you need. Building the query leaves execution to the database connection.

use Atom\Database\Sql\Op;
use Atom\Database\Sql\Query;

Select columns

Pass the table to select() and list the columns with columns(). When you omit columns(), the builder selects all columns.

$query = Query::select("products")
    ->columns("id", "name", "price");

Filter rows

where() checks equality when given a single value. Repeated calls combine the conditions with AND. Use an Op helper to express a comparison such as greater than or equal to.

$query = Query::select("products")
    ->columns("id", "name", "price")
    ->where("active", true)
    ->where("price", Op::gte(10));
Filter Meaning
where("id", [1, 2, 3]) Match any ID in the list.
where("deleted_at", null) Match rows where the column is NULL.
where("name", Op::contains($term)) Find literal text within the name.
where("name", Op::like("Box%")) Match a SQL wildcard pattern.

Op::contains() escapes pattern characters such as % and _. Filter values are bound as parameters. Keep table and column names in application code, or choose them from a fixed list when exposing sort and filter options.

Sort and limit results

orderBy() sorts in ascending order, while orderByDesc() sorts in descending order. A second sort column breaks ties. limit() caps the result, and offset() skips rows from that ordering.

$query = Query::select("products")
    ->columns("id", "name", "price")
    ->where("active", true)
    ->orderByDesc("price")
    ->orderBy("id")
    ->limit(10)
    ->offset(0);

Use aliases to distinguish columns from different tables. A left join keeps a product in the results when its category is missing. Op::column() compares two columns in the join condition.

$query = Query::select("products p")
    ->columns("p.id", "p.name", "c.name categoryName")
    ->leftJoin("categories c", static function ($join): void {
        $join->on("c.id", Op::column("p.category_id"));
    });

Build write statements

Use insert(), update(), and delete() to build write statements. Add a condition to target the intended rows when updating or deleting.

$insert = Query::insert("products")->values(["name" => "Desk lamp"]);
$update = Query::update("products")->set(["price" => 24])->where("id", 42);
$delete = Query::delete("products")->where("id", 42);

See Executing queries to run a statement and read its results.