CakeFest 2024: The Official CakePHP Conference

Функции SQLite (PDO_SQLITE)

Введение

PDO_SQLITE — это драйвер, который реализует интерфейс Data Objects (PDO) для обеспечения доступа к базам данных SQLite 3.

Замечание:

PDO_SQLITE позволяет использовать строки помимо потоков вместе с PDO::PARAM_LOB.

Установка

Драйвер PDO_SQLITE PDO доступен по умолчанию. Для отключения используйте --without-pdo-sqlite[=DIR], где [=DIR] - директория, куда установлен sqlite. Начиная с PHP 7.4.0 требуется библиотека » libsqlite версии 3.5.0 или новее. Ранее встроенный из коробки libsqlite мог использовался вместо этого, и был значением по умолчанию, если опция [=DIR] не задана.

Замечание: Дополнительная настройка на Windows с PHP 7.4.0

Чтобы модуль работал, системной переменной PATH, которую содержит операционная система Windows, дают доступ к DLL-файлам. Раздел FAQ «Как добавить директорию PHP в переменную PATH в Windows» рассказывает, как это сделать. Не рекомендуют копировать DLL-файлы из директории PHP в системную папку Windows, хотя это также решает проблему (потому что системная директория по умолчанию записана в переменной PATH). Модулю нужны следующие файлы в переменной PATH: libsqlite3.dll.

Содержание

  • PDO_SQLITE DSN — Соединение с базой данных SQLite
  • PDO::sqliteCreateAggregate — Регистрация агрегирующей пользовательской функции для использования в SQL-запросах
  • PDO::sqliteCreateCollation — Регистрация пользовательской функции сортировки для использования в SQL-запросах
  • PDO::sqliteCreateFunction — Регистрация пользовательской функции для использования в SQL-запросах
add a note

User Contributed Notes 4 notes

up
10
aidan at php dot net
18 years ago
If you receive an error while trying to write to a sqlite database (update, delete, drop):

Warning: PDO::query() [function.query]: SQLSTATE[HY000]: General error: 1 unable to open database

The folder that houses the database file must be writeable.
up
4
ohcc at 163 dot com
3 years ago
With PDO SQLite driver, calculation within an SQL with multiple ? may not get results as you expect.

<?php
// ....
$stmt = $PDO->prepare('SELECT * FROM `X` WHERE `TimeUpdated`+?>?');
$stmt->execute([3600, time()]);
$data = $stmt->fetchAll();
print_r($data);
?>

To get the right results, you have more than 3 solutions.

1. Change 'SELECT * FROM `X` WHERE `TimeUpdated`+?>?' to 'SELECT * FROM `X` WHERE `TimeUpdated`>?' and do the math using Php (ie: $stmt->execute([time()-3600]); ).

2. Use PdoStatement::bindParam or PdoStatement::bindValue, and set the parameter type to PDO::PARAM_INT.

3. Change 'SELECT * FROM `X` WHERE `TimeUpdated`+?>?' to 'SELECT * FROM `X` WHERE `TimeUpdated`+?>?+0', here '?+0' may be replaced by another math function or another calculation, such as 'abs(?)', you can even wrap both ? with a math calculation.
up
4
nospam8715 at dririan dot com
11 years ago
Instead of compiling an old version of SQLite to create a database using an older database format that the version of SQLite bundled with PDO can handle, you can (much more easily) just run the query "PRAGMA legacy_file_format = TRUE;" BEFORE creating the database (if you have an existing database, run ".dump" from the sqlite shell on your database, run the sqlite shell on a new database, run the PRAGMA, then paste the contents of the .dump). That will ensure SQLite creates a database readable by SQLite 3.0 and later.
up
-1
Duffalo
17 years ago
Note that as of the date of this post, PDO_SQLITE will not interact with database files created with the current version of the SQLite console application, sqlite-3.3.6.

It is currently necessary to obtain version 3.2.8, available from http://www.sqlite.org/ but only by entering the URI manually, as there is no link. Go to http://www.sqlite.org/download.html and find the URI of the version you're looking for, then make the appropriate version number substitution.
To Top