Update of "db"
Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Artifact ID: | 479271f818667534622ec4a99c11f35a2172c48f |
---|---|
Page Name: | db |
Date: | 2014-03-20 06:39:31 |
Original User: | mario |
Mimetype: | text/x-markdown |
Parent: | ec8f5257646c7335955d180f5162e87fee77b668 (diff) |
Next | 57514a38c37ea790b9467ce8dbc899d9b75291c6 |
db()
db.php is a lightweight wrapper for PDO. It allows some flexibility with passing scalar parameters, and adds new placeholders for array binding.
Placeholders
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. |
:& |
| Named column = :param comparison conjoined with AND . |
:| |
| Named Named column = :param comparison conjoined with OR . |
:, |
| Named column=:param list, typically for INSERT statements. |
Identifiers | ||
?: |
| Expands array key names into escaped column identifier list. |
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.
It can be construed manually however with:
db("connect", "mysql:*", $user, $pw);
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(?,?)")
->execute(array(1,2));
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.";