PHP utility collection with hybrid and fluent APIs.

⌈⌋ branch:  hybrid7 libraries



db.php is a lightweight wrapper for PDO. It allows some flexibility with passing scalar parameters, and adds new placeholders for array binding.


List params Expanded Usage
? ? A single scalar value (as in PDO).
?? ?, ?, ? List of scalars.
Named params    
:name :name Named parameter (as in PDO).
:: :a, :b, :c Extracts named array into list of named placeholders.
:& x=:x AND y=:y Named column = :param comparison conjoined with AND.
:| x=:x OR y=:y Named Named column = :param comparison conjoined with OR.
:, x=:x, y=:y Named column=:param list, typically for INSERT statements.
?: a, b, c Expands array key names into escaped column identifier list.
:* SQL and args Takes a list of SQL+parameter pairs. Only interpolates the SQL if the array is non-empty. Allows to nest expressions and complex parameters.

Parameter passing

db() takes a SQL query as first parameter, and allows an arbitrary number of indexed or array arguments thereafter.

It will bind function arguments to a single placeholder each:

db("SELECT ?,?,?", 1, 2, 3)

An array arg will be consumed through complex placeholders:

db("SELECT ??, ??", array(1, 2, 3), array(4, 5, 6));

For indexed parameterization, the order of arguments needs to associate them exactly with the placeholders; obviously.

For named parameters that's not relevant. They have to be passed as array with alphanumeric indexes, and not literal db() arguments, of course:

db("SELECT ::", array("key"=>1, "var"=>2));

Keys need to be unique currently.

Result wrapper

Queries don't return a plain PDO handle. They're wrapped in a db_result{}, which still allows iterations:

foreach (db("SELECT * FROM all") as $row) {

Where dual-access with ->property or ["array"] syntax is permitted:

   print $row->value;
   print $row["value"]

But the result set also allows just accessing one column from the first row:

print db("SELECT value FROM config")->value;

Alternatively the real PDOStatement methods are also accessible:

db("SELECT * FROM all")->fetchAll()

Database connection

Per default db() just operates on the globally shared $db handle.

The db_wrap{} handle is initialized with:

db(new PDO("sqlite:"));

When calling db() without any params, it will return said PDO instance. Thus allowing raw access to the active database through this global wrapper:

db()->prepare("INSERT INTO tbl VALUES(?,?)")

Token binding

Another common feature of such database wrappers are literal placeholder tokens. db() provides them as {NAME} syntax, for e.g. table name prefixes.

Declaring them is as easy as:

$db()->tokens["PREFIX"] = "dbname.";