PHP 8.5.0 Alpha 1 available for testing

SQLite3::createFunction

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::createFunctionRegistra una función PHP para su uso como función escalar SQL

Descripción

public SQLite3::createFunction(
    string $name,
    callable $callback,
    int $argCount = -1,
    int $flags = 0
): bool

Registra una función PHP o una función de usuario para su uso como función escalar SQL, para su utilización en las consultas SQL.

Parámetros

name

Nombre de la función SQL a crear o redefinir.

callback

El nombre de la función PHP o la función de usuario a aplicar como callback, definiendo el comportamiento de la función SQL.

Esta función debe ser definida como:

callback(mixed $value, mixed ...$values): mixed
value

El primer argumento a pasar a la función SQL.

values

Argumentos adicionales a pasar a la función SQL.

argCount

Número de argumentos que la función SQL acepta. Si este parámetro es -1, la función SQL puede aceptar cualquier número de argumentos.

flags

Una conjunción de operaciones a nivel de bits de indicadores. Actualmente, solo SQLITE3_DETERMINISTIC es soportado, lo cual especifica que la función devuelve siempre el mismo resultado dado los mismos argumentos en una sola instrucción SQL.

Valores devueltos

Devuelve true si la función fue creada con éxito, false si ocurre un error.

Historial de cambios

Versión Descripción
7.1.4 El parámetro flags fue añadido.

Ejemplos

Ejemplo #1 Ejemplo con SQLite3::createFunction()

<?php
function my_udf_md5($string) {
return
hash('md5', $string);
}

$db = new SQLite3('mysqlitedb.db');
$db->createFunction('my_udf_md5', 'my_udf_md5');

var_dump($db->querySingle('SELECT my_udf_md5("test")'));
?>

El resultado del ejemplo sería algo similar a:

string(32) "098f6bcd4621d373cade4e832627b4f6"

add a note

User Contributed Notes 2 notes

up
10
koalay at gmail dot com
15 years ago
Since regular expression is not supported by default SQLite, we can create a user function to do the job.

<?php

$db
= new SQLite3("database.sqlit3", 0666);

// create a function named "preg_match"
// with the php core function "preg_match"
if ($db->createFunction("preg_match", "preg_match", 2) === FALSE)
exit(
"Failed creating function\n");

// this query will then works as expected
$result = $db->query("SELECT * FROM table1 WHERE
preg_match('/^(apple|orange)$/', variable1)"
);

?>
up
-1
bohwaz
13 years ago
In PHP 5.4 there will be a createCollation method to use your custom collation method, to be able to sort datasets using unicode, like this:

<?php
setlocale
(LC_COLLATE, 'fr_FR.UTF-8');
$db->createCollation('PHP_COLLATE', 'strcoll');

$db->query('SELECT * FROM my_table ORDER BY name COLLATE PHP_COLLATE;');
?>

But until this cool feature becomes available, you'll have to do some tricks, like this for french:

<?php
function sqlite3_to_ascii($str, $charset = 'UTF-8')
{
// Don't process empty strings
if (!trim($str))
return
$str;

// We only process non-ascii strings
if (preg_match('!^[[:ascii:]]+$!', $str))
return
$str;

$str = htmlentities($str, ENT_NOQUOTES, $charset);

$str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
$str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str);
$str = preg_replace('#&[^;]+;#', '', $str);

return
$str;
}

$db->createFunction('to_ascii', 'sqlite3_to_ascii', 1);
$res = $db->query('SELECT * FROM test ORDER BY to_ascii(text);');
?>

This will convert non-ascii characters to ascii ones before collation. In fact this won't work with non-latin languages, but for latin-languages it's better than nothing.

Please note that this will slow down about 1.8 times the query (tested on a 10.000 rows table).
To Top