Download the PHP package dg/dibi without Composer
On this page you can find all versions of the php package dg/dibi. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Rated 2.00 based on 1 reviews
Informations about the package dibi
Dibi - smart database layer for PHP
Introduction
Database access functions in PHP are not standardised. This library hides the differences between them, and above all, it gives you a very handy interface.
Support Me
Do you like Dibi? Are you looking forward to the new features?
Thank you!
Installation
Install Dibi via Composer:
The Dibi 5.0 requires PHP version 8.2 and supports PHP up to 8.4.
Usage
Refer to the examples
directory for examples. Dibi documentation is
available on the homepage.
Connecting to database
The database connection is represented by the object Dibi\Connection
:
Alternatively, you can use the dibi
static register, which maintains a connection object in a globally available storage and calls all the functions above it:
In the event of a connection error, it throws Dibi\Exception
.
Queries
We query the database queries by the method query()
which returns Dibi\Result
. Rows are objects Dibi\Row
.
You can try all the examples online at the playground.
Method fetchAssoc() can return a more complex associative array.
You can easily add parameters to the query, note the question mark:
WARNING: Never concatenate parameters to SQL. It would create a SQL injection vulnerability.
Instead of a question mark, so-called modifiers can be used.
In case of failure query()
throws Dibi\Exception
, or one of the descendants:
ConstraintViolationException
- violation of a table constraintForeignKeyConstraintViolationException
- invalid foreign keyNotNullConstraintViolationException
- violation of the NOT NULL conditionUniqueConstraintViolationException
- collides unique index
You can use also shortcuts:
Modifiers
In addition to the ?
wildcard char, we can also use modifiers:
modifier | description |
---|---|
%s | string |
%sN | string, but '' translates as NULL |
%bin | binary data |
%b | boolean |
%i | integer |
%iN | integer, but 0 is translates as NULL |
%f | float |
%d | date (accepts DateTime, string or UNIX timestamp) |
%dt | datetime (accepts DateTime, string or UNIX timestamp) |
%n | identifier, ie the name of the table or column |
%N | identifier, treats period as a common character, ie alias or a database name (%n AS %N or DROP DATABASE %N ) |
%SQL | SQL - directly inserts into SQL (the alternative is Dibi\Literal) |
%ex | SQL expression or array of expressions |
%lmt | special - adds LIMIT to the query |
%ofs | special - adds OFFSET to the query |
Example:
If $name is null, the NULL is inserted into the SQL statement.
If the variable is an array, the modifier is applied to all of its elements and they are inserted into SQL separated by commas:
The modifier %n
is used if the table or column name is a variable. (Beware, do not allow the user to manipulate the content of such a variable):
Three special modifiers are available for LIKE:
modifier | description |
---|---|
%like~ |
the expression starts with a string |
%~like |
the expression ends with a string |
%~like~ |
the expression contains a string |
%like |
the expression matches a string |
Search for names beginning with a string:
Modifiers for arrays
The parameter entered in the SQL query can also be an array. These modifiers determine how to compile the SQL statement:
modifier | result | |
---|---|---|
%and | key1 = value1 AND key2 = value2 AND ... |
|
%or | key1 = value1 OR key2 = value2 OR ... |
|
%a | assoc | key1 = value1, key2 = value2, ... |
%l %in | list | (val1, val2, ...) |
%v | values | (key1, key2, ...) VALUES (value1, value2, ...) |
%m | multi | (key1, key2, ...) VALUES (value1, value2, ...), (value1, value2, ...), ... |
%by | ordering | key1 ASC, key2 DESC ... |
%n | names | key1, key2 AS alias, ... |
Example:
In the WHERE clause modifiers %and
nebo %or
can be used:
The modifier %by
is used to sort, the keys show the columns, and the boolean value will determine whether to sort in ascending order:
Insert, Update & Delete
We insert the data into an SQL query as an associative array. Modifiers and wildcards ?
are not required in these cases.
Multiple INSERT:
Deleting:
Update:
Insert an entry or update if it already exists:
Transaction
There are three methods for dealing with transactions:
Testing
In order to play with Dibi a little, there is a test()
method that you pass parameters like to query()
, but instead of executing the SQL statement, it is echoed on the screen.
The query results can be echoed as a table using $result->dump()
.
These variables are also available:
Complex queries
The parameter may also be an object DateTime
.
Or SQL literal:
Or an expression in which you can use ?
or modifiers:
When updating, modifiers can be placed directly in the keys:
In conditions (ie, for %and
and %or
modifiers), it is not necessary to specify the keys:
Modifiers or wildcards can also be used in expressions:
The %ex
modifier inserts all items of the array into SQL:
Conditions in the SQL
Conditional SQL commands are controlled by three modifiers %if
, %else
, and %end
. The %if
must be at the end of the string representing SQL and is followed by the variable:
The condition can be supplemented by the section %else
:
Conditions can nest together.
Identifiers and strings in SQL
SQL itself goes through processing to meet the conventions of the database. The identifiers (names of tables and columns) can be entered into square brackets or backticks, strings are quoted with single or double quotation marks, but the server always sends what the database asks for. Example:
The quotation marks are duplicated inside the string in SQL.
Result as associative array
Example: returns results as an associative field, where the key will be the value of the id
field:
The greatest power of fetchAssoc()
is reflected in a SQL query joining several tables with different types of joins. The database will make a flat table, fetchAssoc returns the shape.
Example: Let's take a customer and order table (N:M binding) and query:
And we'd like to get a nested associative array by Customer ID and then Order ID:
An associative descriptor has a similar syntax as when you type the array by assigning it to PHP. Thus 'customer_id|order_id'
represents the assignment series $all[$customerId][$orderId] = $row;
sequentially for all rows.
Sometimes it would be useful to associate by the customer's name instead of his ID:
But what if there are more customers with the same name? The table should be in the form of:
So we can distinguish between multiple possible Rimmers using an array. The associative descriptor has a format similar to the assignment, with the sequence array representing []
:
Returning to the example with the customer_id|order_id
descriptor, we will try to list the orders of each customer:
It would be a nice to echo customer name too. But we would have to look for it in the $orders
array. So let's adjust the results to such a shape:
So, between $clientId
and $orderId
, we will also insert an intermediate item. This time not the numbered indexes as we used to distinguish between individual Rimmers, but a database row. The solution is very similar, just remember that the row symbolizes the arrow:
Prefixes & substitutions
Table and column names can contain variable parts. You will first define:
and then use it in SQL. Note that in SQL they are quoted by the colon:
Field data types
Dibi automatically detects the types of query columns and converts fields them to native PHP types. We can also specify the type manually. You can find the possible types in the Dibi\Type
class.
Logger
Dibi has a built-in logger that lets you track all SQL statements executed and measure the length of their duration. Activating the logger:
A more versatile profiler is a Tracy panel that is activated when connected to Nette.
Connect to Nette
In the configuration file, we will register the DI extensions and add the dibi
section to create the required objects and also the database panel in the Tracy debugger bar.
Then the object of connection can be obtained as a service from the container DI, eg: