Executing queries
Inject Atom\Database\DatabaseConnection into a service to use the connection selected in Configuration. The examples use that connection as $db. The same methods accept a SQL string or a statement built with the query builder.
Bind parameters and read one row
Use named placeholders for values in a SQL string. Pass the values in the second argument, keyed by placeholder name. The connection binds them separately from the SQL.
$product = $db->first(
"SELECT id, name, price FROM products WHERE id = :id",
["id" => 42],
);
first() returns an associative array or null when no row matches. In the example, id identifies one product.
Read multiple rows
Use all() to get a list of associative arrays. An empty result is an empty array.
$products = $db->all(
"SELECT id, name, price FROM products WHERE price >= :minimum ORDER BY id",
["minimum" => 10],
);
With a query builder object, the values in conditions are already part of the query:
use Atom\Database\Sql\Query;
$query = Query::select("products")
->columns("id", "name", "price")
->where("active", true);
$products = $db->all($query);
Read one value
Use scalar() for the first column of the first row, such as a count. It returns false when no row is available. A COUNT(*) without grouping still returns a row when there are zero matches.
$count = $db->scalar(
"SELECT COUNT(*) FROM products WHERE price >= :minimum",
["minimum" => 10],
);
Execute a write
Use execute() for inserts, updates, and deletes when you need the affected row count.
$affected = $db->execute(
"UPDATE products SET price = :price WHERE id = :id",
["price" => 24, "id" => 42],
);
Run statements in a transaction
Use transaction() when several statements need to commit together. The callback receives the same connection.
use Atom\Database\DatabaseConnection;
$db->transaction(static function (DatabaseConnection $connection): void {
$sql = "UPDATE products SET price = :price WHERE id = :id";
$connection->execute($sql, ["price" => 24, "id" => 42]);
$connection->execute($sql, ["price" => 32, "id" => 43]);
});
Atom commits when the callback completes and rolls back if an exception escapes it.