In follow up to Csaba Gabor's function (see below) that allows for multi-statement queries to be executed via sqlite_query() this alternative implementation avoids a problem with Csaba's version (which prevents multi-statement constructs like CREATE TRIGGER from being parsed correctly).
<?php
function sqlite_query_multi ($db, $query) {
//
// sqlite_query() rewritten to support concatenated SQL statements.
//
// This method works around the sqlite_query() deficiency by splitting
// queries into two parts; the first part comprising all the statements
// except the last one (executed via sqlite_exec) and then the last
// statement (executed via sqlite_query).
//
// This allows the result of the last SELECT statement in a multi-statement
// query to be accessed regardless of the SQL statements that came before it.
// It also allows execution of arbitrary multi-statement programs regardless
// whether the result is needed, subject to the following constraint:
//
// This method requires that the last statement in a multi-statement query
// is a valid "stand-alone" SQL statement. If it is not (eg, the "END;" of
// a multi-statement construct such as CREATE TRIGGER) append an additional
// ";" (ie, a NULL statement). Normally this should not be needed because
// almost all the multi-statement constructs I can think of should have a
// stand-alone statement following them (ie, to makes use of the construct).
//
$pattern = '/^(.*;)(.*;)/s';
if ( preg_match($pattern,$query,$match) ) {
// multi-statement query
sqlite_exec($db,$match[1]);
$result = sqlite_query($db,$match[2]);
} else {
// single-statement query
$result = sqlite_query($db,$query);
}
return (@$result);
}
?>
sqlite_query
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_query — 指定したデータベースに対してクエリを実行し、結果ハンドル を返す
説明
オブジェクト指向言語型スタイル (メソッド):
指定したデータベースにより query で指定した SQL ステートメントを実行します。
パラメータ
- dbhandle
-
SQLite データベースリソース。手続きに従って、 sqlite_open() から返されます。 このパラメータは、 オブジェクト指向言語型メソッドを使用する場合は不要です。
- query
-
実行するクエリ
クエリ内のデータは 適切にエスケープ する必要があります。
- result_type
-
オプションの result_type パラメータには定数を指定でき、返される配列の添字を定義します。 SQLITE_ASSOC を用いると、連想配列の添字(名前フィールド)のみが 返されます。一方、SQLITE_NUM は、 数値の添字(フィールド番号)のみを返します。SQLITE_BOTH は、 連想配列の添字と数値の添字の両方を返します。 SQLITE_BOTH がこの関数のデフォルトです。
- error_msg
-
もしエラーが発生した場合、ここに保存されます。SQL 構文のエラーは sqlite_last_error() 関数で取得することが できないため、このパラメータが特に重要となります。
注意: (MySQL のような)他のデータベースエクステンションとの互換性のため、 2 種類の構文がサポートされています。 推奨されるのは最初の構文で、dbhandle パラメータを 関数の最初のパラメータとするものです。
返り値
この関数は結果ハンドル、もしくは失敗時に FALSE を返します。 レコードを返すクエリの場合、結果ハンドルは sqlite_fetch_array() や sqlite_seek() のような関数で使用することができます。
クエリの型によらず、この関数はクエリが失敗した場合にFALSE を返し ます。
sqlite_query() は、バッファリングされ、シーク可 能な結果ハンドルを返します。これは、レコードにランダムにアクセスす る必要がある小さなクエリの場合に有用です。バッファリングされた結果 ハンドルは、結果全体を保持するためのメモリを確保し、結果が取得され るまでは値を返しません。 データに連続的にアクセスしたい場合、かわりにより高性能な sqlite_unbuffered_query() を使用することが 推奨されます。
変更履歴
| バージョン | 説明 |
|---|---|
| 5.1.0 | error_msg パラメータが追加されました。 |
注意
SQLiteは、セミコロンで区切られた複数のクエリを実行します。 これにより、ファイルからロードするかスクリプトに埋め込んだ SQL をバッチ実行することができます。 しかしながら、これは関数の結果が使用されない場合のみ動作します。 使用されない場合、最初の SQL ステートメントのみ実行されます。 関数 sqlite_exec() は常に複数の SQL ステートメントを実行します。
複数のクエリを実行する際、この関数の返り値は、エラーの場合に FALSEとなります。しかし、それ以外の場合は不定となります。 (成功した場合にTRUEとなるか、結果ハンドルを返す可能性があります)
参考
- sqlite_unbuffered_query() - 事前取得していないクエリを実行し、全てのデータをバッファリングする
- sqlite_array_query() - 指定したデータベースに対してクエリを実行し、配列を返す
sqlite_query
05-Aug-2009 06:11
05-Feb-2008 09:58
I suppose this could be useful for users attempting to use a sqlite database for the first time.
<?php
$database = new SQLiteDatabase($yourfile, 0666, $error);
if (!$database) {
$error = (file_exists($yourfile)) ? "Impossible to open, check permissions" : "Impossible to create, check permissions";
die($error);
}
$query = $database->query("SELECT name FROM sqlite_master WHERE type='table'", SQLITE_ASSOC, $query_error); #Lists all tables
if ($query_error)
die("Error: $query_error"); #This means that most probably we catch a syntax error
if (!$query)
die("Impossible to execute query.") #As reported above, this means that the db owner is different from the web server's one, but we did not commit any syntax mistake.
print $query->numRows();
while ($row = $query->fetch())
print($row['name']."\n");
?>
i suppose that the example above is also useful because it will list all the tables created, giving also comprehension of what appens when managing a sqlite database in OO mode.
27-Oct-2005 02:32
Correction:
sqlite_query will return NULL if the web server cannot write to the sqlite database file.
(please correct the previous post and delete this one)
24-Oct-2005 04:35
sqlite_open will return NULL if the web server cannot write to the sqlite database file.
I saw the following message in my web server error log:
PHP Warning: sqlite_query(): (null) ...
It turns out that the sqlite database file was owned by a user other than the one the web server was running as. In my case, it was a Linux system running Apache (which was running under the context of user apache). The sqlite database file was owned by root. I changed ownership of the file to user apache and now it works! The sqlite_open call now returns a valid result handle.
Jason Aeschilman
While reading the manual at sqlite.org, I can answer for the quotes in strings. You should put two quote to get one.
insert into atable values ( '5 O''Clock');
30-Apr-2004 01:41
The function below allows you to submit multiple queries in one shot to a SQLITE database, and will return whatever you would get for the final query.
function sqlite_query_multi ($db, $query) {
// submit multiple queries (separated by ;) to $db
// and return the result from the last one
$multiSQL = "/('[^']*'|\"[^\"]*\"|[^;'\"])*;/";
preg_match_all ($multiSQL, "$query;", $aSQL);
for ($i=sizeof($aSQL=$aSQL[0]);$i--;)
if (!($trim=trim(substr($aSQL[$i],0,-1))))
unset ($aSQL[$i]);
else $aSQL[$i] = "$trim;";
foreach ($aSQL as $i => $sql)
$dbRes = sqlite_query ($db, $sql);
return (@$dbRes);
}
The section below illustrates the above function:
$db = sqlite_open(":memory:", 0666, $sqliteerror);
$query = <<<EOD
CREATE TABLE foo (bar INTEGER PRIMARY KEY, baz TEXT);
INSERT INTO foo VALUES (Null, 'Hi');
INSERT INTO foo VALUES (Null, 'Mom');
SELECT * FROM foo;
EOD;
$dbRes = sqlite_query_multi ($db, $query); // 4 statements
while (sqlite_has_more($dbRes))
var_dump(sqlite_fetch_array($dbRes, SQLITE_ASSOC));
Csaba Gabor
