PHP Velho Oeste 2024

sqlite_create_function

SQLiteDatabase::createFunction

(PHP 5 < 5.4.0, sqlite >= 1.0.0)

sqlite_create_function -- SQLiteDatabase::createFunction SQLステートメントで使用するために"通常の"ユーザー定義関数を登録する

説明

public sqlite_create_function ( resource $dbhandle , string $function_name , callable $callback [, int $num_args = -1 ] ) : void

オブジェクト指向型 (メソッド):

SQLiteDatabase::createFunction ( string $function_name , callable $callback [, int $num_args = -1 ] ) : void

sqlite_create_function() により、SQLiteにPHP関数 をUDF (ユーザー定義関数)として登録することが可能で す。この関数は、SQLステートメントの中からコールできます。

UDFは、SELECTおよびUPDATEステートメント、そして、トリガーの中のよう に関数をコールできる全てのSQLステートメントで使用可能です。

パラメータ

dbhandle

SQLite データベースリソース。手続きに従って、 sqlite_open() から返されます。 このパラメータは、 オブジェクト指向言語型メソッドを使用する場合は不要です。

function_name

SQL ステートメントで使用する関数名

callback

定義された SQL 関数を処理するためのコールバック関数

注意: コールバック関数は SQLite で有効な型 (例えば スカラー型) を返す必要があります

num_args

コールバック関数が規定の引数の数を受け入れるかどうかを決定するため SQLite パーサに渡すヒント

注意: (MySQL のような)他のデータベースエクステンションとの互換性のため、 2 種類の構文がサポートされています。 推奨されるのは最初の構文で、dbhandle パラメータを 関数の最初のパラメータとするものです。

返り値

値を返しません。

例1 sqlite_create_function() の例

<?php
function md5_and_reverse($string)
{
    return 
strrev(md5($string));
}

if (
$dbhandle sqlite_open('mysqlitedb'0666$sqliteerror)) {

    
sqlite_create_function($dbhandle'md5rev''md5_and_reverse'1);

    
$sql  'SELECT md5rev(filename) FROM files';
    
$rows sqlite_array_query($dbhandle$sql);
} else {
    echo 
'Error opening sqlite db: ' $sqliteerror;
    exit;
}
?>

この例では、文字列のMD5サムを計算し、順番を反転する関数が記述されています。 このSQLステートメントが実行された場合、 関数により変換されたファイル名の値を返します。 $rows により返されるデータには、 処理結果が含まれています。

この技術の美しいところは、データのクエリーを実行した後で foreach ループにより結果を処理する必要がないことです。

PHP は、データベースが最初にオープンされる際に php という名前の特別な関数を登録します。 このphp関数は、事前に登録することなしにあらゆるPHP関数をコールする ために使用可能です。

例2 PHP 関数の使用例

<?php
$rows 
sqlite_array_query($dbhandle"SELECT php('md5', filename) from files");
?>

この例は、データベースの各 filename カラムにつ いて md5() をコールし、その結果を $rowsに返します。

注意:

性能上の理由から、PHPはUDFとの間で送受信されるバイナリデータを自動 的にエンコード/デコードしません。この方法でバイナリデータを処理す る必要がある場合、パラメータを手動でエンコード/デコードし、 値を返すようにする必要があります。 詳細については、sqlite_udf_encode_binary() およびsqlite_udf_decode_binary()を参照して下さ い。

ヒント

適用するアプリケーションの主要な要求が高い性能でない限り、バイナリ データの処理を行うためにUDFを使用することは推奨されません。

ヒント

SQLiteのネーティブSQL関数をオーバーライドするために sqlite_create_function()および sqlite_create_aggregate()も使用可能です。

参考

add a note add a note

User Contributed Notes 4 notes

up
1
anrdaemon at freemail dot ru
7 years ago
The (probably) all too often requested regexp() function actually works just fine.

<?php

$db
= new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$db->sqliteCreateFunction('regexp', function($y, $x) { return preg_match('/' . addcslashes($y, '/') . '/', $x); }, 2);

$db->query('SELECT ("Things!" REGEXP "^T") `result`');

?>
up
1
Dodolidet
12 years ago
Although you can create an UDF named 'regexp()', I think it won't be registered as REGEXP operator..

<?php
//registering REGEXP
function my_sqlite_regexp($x,$y){
    return (int)
preg_match("`$y`i",$x);
}
echo
$db->createFunction('regexp','my_sqlite_regexp',2);

//testing regexp as function, working
$res = $db->query("SELECT * FROM x WHERE regexp(c,'h')", SQLITE_ASSOC , $err) ;

//testing regexp as operator, not working, near "REGEXP": syntax error
$res = $db->query("SELECT * FROM x WHERE c REGEXP 'h'", SQLITE_ASSOC , $err);
?>

I'd also swapped the function parameters $x and $y, but also not works..
-----
From SQLite documentation:
"The REGEXP operator is a special syntax for the regexp() user function. No regexp() user function is defined by default and so use of the REGEXP operator will normally result in an error message. If a application-defined SQL function named "regexp" is added at run-time, that function will be called in order to implement the REGEXP operator."
up
1
info at myphp dot it
19 years ago
The function can be a method of a class:

<?php

class sqlite_function {

    function
md5($value)
    {
        return
md5($value);
    }

}

$dbhandle = sqlite_open('SQLiteDB');

sqlite_create_function($dbhandle, 'md5', array('sqlite_function', 'md5'), 1);

// From now on, you can use md5 function inside your SQL statements

?>

It works fine :)
up
0
Brett
18 years ago
In my previous comment, there was an error in the code which was causing the issue.

Removing the surrounding quotes from from_unixtime()'s return value solved the issue, and so UDFs _do work_ from within DELETEs and INSERTs!  Yay!

<?php

// SQLite UDF
// Mimic MySQL FROM_UNIXTIME
function from_unixtime($unixtime)
{
    return
date('Y-m-d H:i:s', $unixtime);  // no surrouding quotes
}

?>
To Top