Php pdo sqlite примеры

Подключение к базе данных SQLite3 с помощью PHP PDO

Это начало мини-курса по использованию SQLite3 для PHP совместно c PDO. Будет 7-8 уроков, в которых я подробно расскажу, как использовать SQLite3 совместно c PDO в PHP приложении. Мини курс рассчитан на новичков и является отличным пособием для старта.

В этом уроке я покажу вам, как установить соединение с базой данных SQLite из PHP с помощью PDO. По умолчанию PHP включает расширение SQLite, поэтому вам не нужно дополнительно настраивать PHP, чтобы он работал с SQLite.

Структура проекта. Composer.

Сначала создайте директорию проекта. Затем в ней создайте новый файл composer.json со следующим кодом:

Здесь мы сопоставляем пространство имен App с папкой /app .

Затем создайте еще одну директорию с именем db для хранения файла базы данных SQLite.

После этого откройте инструмент командной строки, перейдите в корневую директорию проекта и введите следующую команду:

Появится следующее сообщение:

>composer update Loading composer repositories with package information Updating dependencies (including require-dev) Nothing to install or update Generating autoload files

Кроме того, Composer также создает новую папку с именем vendor , как показано ниже:

Структура проекта

Наконец, создайте файл с именем index.php в корневой директории и добавьте следующий код:

require 'vendor/autoload.php';

Отныне, если мы хотим использовать какой-либо класс в директории приложения, нам просто нужно объявить и использовать его.

Установка соединения с базой данных SQLite

Сначала создайте новый файл Config.php в директории приложения и добавьте новый класс с именем Config следующим образом:

Константа PATH_TO_SQLITE_FILE используется для хранения пути к файлу базы данных sqlite, который находится в папке db .

Во-вторых, создайте новый файл SQLiteConnection.php и добавьте класс SQLiteConnection следующим образом:

pdo == null) < $this->pdo = new \PDO("sqlite:" . Config::PATH_TO_SQLITE_FILE); if (!filesize(self::SQLITE_FILE)) throw new \Exception('There are no tables in the database!'); > return $this->pdo; > >

Чтобы установить соединение с базой данных SQLite, нам нужно создать новый экземпляр класса PDO и передать строку соединения конструктору объекта PDO .

Предположим, что файл базы данных SQLite находится в папке db , мы используем следующую строку подключения:

Поскольку мы храним путь к файлу базы данных sqlite в классе Config , мы просто используем его для построения строки подключения.

Обратите внимание, что когда PHP подключается к базе данных SQLite, если она не существует, PHP создаст новый файл базы данных SQLite.

$this->pdo используется для хранения экземпляра объекта PDO. В методе connect() мы проверяем, установлено ли соединение с базой данных. Если нет, мы создаем новый экземпляр объекта PDO , в противном случае мы возвращаем объект PDO .

Если необходимо сгенерировать файла автозагрузки заново:

Чтобы установить соединение с базой данных SQLite, мы используем следующий код в файле index.php :

connect(); if ($pdo != null) echo 'Connected to the SQLite database successfully!'; else echo 'Whoops, could not connect to the SQLite database!';

Если вы проверите папку db , вы увидите файл с именем phpsqlite.db .

Создание БД

Когда вы создаете новый экземпляр PDO , он всегда будет выдавать исключение PDOException в случае сбоя соединения.

Для обработки исключения вы можете использовать блок try catch следующим образом:

try < $this->pdo = new \PDO("sqlite:" . Config::PATH_TO_SQLITE_FILE); > catch (\PDOException $e) < // handle the exception here >

В этом уроке я показал, как настроить структуру проекта PHP и установить соединение с базой данных SQLite.

Источник

Функции 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

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

User Contributed Notes 8 notes

With PDO SQLite driver, calculation within an SQL with multiple ? may not get results as you expect.

// .
$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.

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.

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.

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.

This page has been out of date for some time — Installation specifically.

As of PHP 5.4 sqlite is no longer part of PHP and in only available through PECL

If you get an error reporting «invalid resource» when trying to query the database table and looping through it, the version of the SQLite extension compiled in to PHP might be incompatible with the version that had created the database (like SQLite 2.x vs 3.x).

The database open itself might be successful, failing only when querying.

$dbh = new PDO(‘sqlite:/tmp/foo.db’); // success
foreach ($dbh->query(‘SELECT * FROM bar’) as $row) // prints invalid resource
// .

After wrestling with «General error: 5 database is locked» errors for a highly concurrent project I finally wrapped the PDO transaction code with a semaphore. No errors since.

Obviously only works if all processes use the subclass and wrap database modifying statements in beginTransaction() .. commit(). The same could be achieved with flock() if semaphore is not available on your system but will be slower.

class SQLitePDO extends PDO function __construct ( $filename ) $filename = realpath ( $filename );
parent :: __construct ( ‘sqlite:’ . $filename );

$key = ftok ( $filename , ‘a’ );
$this -> sem = sem_get ( $key );
>

function beginTransaction () sem_acquire ( $this -> sem );
return parent :: beginTransaction ();
>

function commit () $success = parent :: commit ();
sem_release ( $this -> sem );
return $success ;
>

function rollBack () $success = parent :: rollBack ();
sem_release ( $this -> sem );
return $success ;
>
>
?>

Issue:
Error: SQLSTATE[HY000]: General error: 1 unsupported file format

Resolution:
To solve this (and/or many issues) involving this type of error, I assumed the error to be generated from php. Well, it was to an extent. The sqlite pdo code offered the solution:

I researched the error by grep’ing the php source code and found the error string to come from php-5.1.4/ext/pdo_sqlite/sqlite/src/prepare.c, lines 265:278 :

/*
** file_format==1 Version 3.0.0.
** file_format==2 Version 3.1.3.
** file_format==3 Version 3.1.4.
**
** Version 3.0 can only use files with file_format==1. Version 3.1.3
** can read and write files with file_format==1 or file_format==2.
** Version 3.1.4 can read and write file formats 1, 2 and 3.
*/
if( meta[1]>3 ) sqlite3BtreeCloseCursor(curMain);
sqlite3SetString(pzErrMsg, «unsupported file format», (char*)0);
return SQLITE_ERROR;
>

This is interesting as I am running SQLite version 3.3.5 which the databases were created in. I see that the SQLite PDO source in the php source is :
# cat ext/pdo_sqlite/sqlite/VERSION
3.2.8

Also as a side note, to get SQLite compiled as a PDO, I had to:

1) configure with
.
—enable-pdo=shared \
—with-sqlite=shared \
—with-pdo-sqlite=shared
—with-zlib
. \
‘make && make install’ if configure is successful.

2) Make sure the pdo libs were copied/installed to the correct directory. On my installation it was /usr/local/include/php/ext/pdo/

3) Make these changes in my php.ini:
— change ‘ extension_dir = «./» ‘ to ‘ extension_dir=»/usr/local/include/php/ext/pdo/» ‘
— add/edit in this order:
extension=pdo.so
extension=pdo_sqlite.so
extension=sqlite.so

4) test php with : ‘php -m’ at the command line and solve any issues from there. Mostly php.ini config issues. Also restart the http service!

Оцените статью