Не работает sqlite php

how to enable sqlite3 for php?

This also added a PHP configuration file in /etc/php5/apache2/conf.d; it even restarted Apache, although for some reason I had to restart it again for the change to take effect.

Good answer but I needed to restart apache to get the module to show up (eg. sudo service apache2 restart )

For PHP7, alter the below for your version of PHP (7.0, 7.2, 7.4, etc) and run

sudo apt-get install php7.0-sqlite3 

Edit: This answer is outdated, but can’t be removed because it’s accepted. Please see the solution from Stacey Richards for the correct answer.

 sudo apt-get install php5-cli php5-dev make sudo apt-get install libsqlite3-0 libsqlite3-dev sudo apt-get install php5-sqlite3 sudo apt-get remove php5-sqlite3 cd ~ wget http://pecl.php.net/get/sqlite3-0.6.tgz tar -zxf sqlite3-0.6.tgz cd sqlite3-0.6/ sudo phpize sudo ./configure sudo make sudo make install sudo apache2ctl restart 

The 2nd to last command should be sudo checkinstall (after running sudo apt-get install checkinstall . Why use an OS with a package manager if you’re not going to use it?

Best advice for this understandably annoying situation: meta.stackoverflow.com/a/276564/2778484 and meta.stackexchange.com/questions/78438/… (fixing the answer with an edit is obviously not possible since it’s beyond just a syntax error).

The accepted answer is not complete without the remainder of instructions (paraphrased below) from the forum thread linked to:

cd /etc/php5/conf.d cat > sqlite3.ini # configuration for php SQLite3 module extension=sqlite3.so ^D sudo /etc/init.d/apache2 restart 

At least on Ubuntu 14.04, this step is not needed, as there already is a sqlite3.ini as /etc/php5/mods-available/sqlite3.ini

Читайте также:  Множество является в питон

For Ubuntu 18.04 and PHP 7.2:

sudo apt install php-sqlite3

The SQLite3 PDO driver is named SQLite, not SQLite3, so you can do:

The Debian/Ubuntu way for php-7.2, php-7.3 & php-7.4 (e.g. the [234] part)

sudo apt install php7.[234]-sqlite sudo phpenmod sqlite3 

Be sure to note that on Windows Subsystem for Linux version 1 (WSL1) the (file-)locking system for SQlite is broken.

one thing I want to add , before you try to install

apt-get install php5-sqlite 
apt-get install php5-sqlite3 

search the given package is available or not :-

php5-rrd - rrd module for PHP 5 php5-sasl - Cyrus SASL extension for PHP 5 php5-snmp - SNMP module for php5 **php5-sqlite - SQLite module for php5** php5-svn - PHP Bindings for the Subversion Revision control system php5-sybase - Sybase / MS SQL Server module for php5 

Here you get an idea about whether your version support or not .. in my system I get php5-sqlite — SQLite module for php5 so I prefer to install

**apt-get install php5-sqlite** 

Источник

Не создается таблица средствами PHP в БД SQLite3

Всех с Новым 2015 годом и доброго времени суток. Образовалась некоторая проблема. Использую OpenServer для изучения PHP OOP. Все работало нормально, до начала совместного использования PHP 5.4 c SQLite3. Задача такая: создать файл БД и в нем создать пару таблиц.
Файл создается без проблем, но вот запросы на создание таблиц никак не желают выполняться. Есть подозрение на настройки OpenServer, хотя, возможно, и ошибки в коде. Код прилагается:

class NewsDB implements INewsDB < function saveNews($title, $category, $description, $source)<>function getNews()<> function deleteNews($id)<> const DB_NAME = 'C:\OpenServer\domains\mysite.local\news.db'; protected $_db; public function __construct()< if(is_file(self::DB_NAME))< $this->_db = new SQLite3(self::DB_NAME);> else< $this->_db = new SQLite3(self::DB_NAME); $sql = "CREATE TABLE msgs( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, category INTEGER, description TEXT, source TEXT, datetime INTEGER)"; $this->_db->exec($sgl) or die($this->_db->lastErrorMsg()); $sql = 'CREATE TABLE category( id INTEGER, name TEXT)'; $this->_db->exec($sgl) or die($this->_db->lastErrorMsg()); $sql = "INSERT INTO category(id, name) SELECT 1 as id, 'Политика' as name UNION SELECT 2 as id, 'Культура' as name UNION SELECT 3 as id, 'Спорт' as name "; $this->_db->exec($sgl) or die($this->_db->lastErrorMsg());> > public function __destruct()< unset($this->_db); > > $news = new NewsDB; 

1 ответ 1

Попробуйте заменить команду в двух строчках

$this->_db->exec($sgl) or die($this->_db->lastErrorMsg()); 
$this->_db->query($sgl) or die($this->_db->lastErrorMsg()); 

Источник

PHP SQLite Не записывает данные в базу

интересная ситуация. Написал небольшой чат на PHP с авторизацией перед каждой отправкой сообщения, но это не суть. На локальном компьютере всё работало хорошо, данные из базы читались и в базу записывались, а вот когда загрузил всё на сервер, работать не перестал только скрипт по чтению данных из БД. Система — Linux Debian11 Php7.4, Установлена php7.4-sqlite. На файле базы данных стоит 777 разрешение. Сам Php скрипт отрабатывает хорошо, без ошибок, но данные в базе не появляются Пожалуйста, помогите. Ниже скрипт

prepare($query); $stmt->bindParam(':nickname', $nickname); $stmt->execute(); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (!$user) < if(!($password == "") && !($nickname == "") && !($message == "")) < // Если пользователь не существует, создаем нового пользователя $insertQuery = 'INSERT INTO users (nickname, password) VALUES (:nickname, :password)'; $insertStmt = $db->prepare($insertQuery); $insertStmt->bindParam(':nickname', $nickname); $insertStmt->bindParam(':password', $password); $insertStmt->execute(); $insertMessageQuery = 'INSERT INTO messages (nickname, message) VALUES (:nickname, :message)'; $insertMessageStmt = $db->prepare($insertMessageQuery); $insertMessageStmt->bindParam(':nickname', $nickname); $insertMessageStmt->bindParam(':message', $message); $insertMessageStmt->execute(); $report = ""; // Преобразование отчета в JSON $response = array('report' => $report); $responseJson = json_encode($response); // Возвращение отчета в JSON формате echo $responseJson; > else < $report = "Не оставляйте поля пустыми!"; // Преобразование отчета в JSON $response = array('report' =>$report); $responseJson = json_encode($response); // Возвращение отчета в JSON формате echo $responseJson; exit; > > else < // Проверяем правильность пароля if ($user['password'] === $password) < $insertMessageQuery = 'INSERT INTO messages (nickname, message) VALUES (:nickname, :message)'; $insertMessageStmt = $db->prepare($insertMessageQuery); $insertMessageStmt->bindParam(':nickname', $nickname); $insertMessageStmt->bindParam(':message', $message); $insertMessageStmt->execute(); $report = ""; // Преобразование отчета в JSON $response = array('report' => $report); $responseJson = json_encode($response); // Возвращение отчета в JSON формате echo $responseJson; > else < // Возвращаем ошибку, если пароль неверный $report = "Пользователь уже зарегистрирован - вы ввели неверный пароль."; // Преобразование отчета в JSON $response = array('report' =>$report); $responseJson = json_encode($response); // Возвращение отчета в JSON формате echo $responseJson; exit; > > ?> 

Источник

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