(PHP 8 >= 8.4.0)
Pdo\Sqlite::createFunction — Registers a user-defined function for use in SQL statements
$function_name
,$callback
,$num_args
= -1,$flags
= 0
This method allows PHP function to be registered with SQLite as a
user-defined function, so that it can be called within SQL queries.
The defined function can be used in any SQL query that allows function calls,
for example SELECT
, UPDATE
, or triggers.
By using this method it is possible to override native SQL functions.
function_name
callback
Note: Callback functions should return a type understood by SQLite (i.e. scalar type).
This function need to be defined as:
value
The first argument passed to the SQL function.
values
Further arguments passed to the SQL function.
num_args
-1
,
then the SQL function may take any number of arguments.
flags
Pdo\Sqlite::DETERMINISTIC
is supported,
which specifies that the function always returns the same result given
the same inputs within a single SQL statement.
Example #1 Pdo\Sqlite::createFunction() example
In this example, we have a function that calculates the SHA256 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.
The beauty of this technique is that there is no need to process the result using a foreach loop after the query.
<?php
function sha256_and_reverse($string)
{
return strrev(hash('sha256', $string));
}
$db = new Pdo\Sqlite('sqlite::sqlitedb');
$db->sqliteCreateFunction('sha256rev', 'sha256_and_reverse', 1);
$rows = $db->query('SELECT sha256rev(filename) FROM files')->fetchAll();
?>