Php sqlite3 обработка ошибок

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::enableExceptions
Включить выброс исключений

Описание

public SQLite3::enableExceptions(bool $enable = false): bool

Возвращаемые значения

Возвращает старое значение; true, если исключения включены, false в противном случае.

Примеры

Пример #1 Пример использования SQLite3::enableExceptions()

<?php
$sqlite
= new SQLite3(':memory:');
try {
$sqlite->exec('create table foo');
$sqlite->enableExceptions(true);
$sqlite->exec('create table bar');
} catch (
Exception $e) {
echo
'Поймано исключение: ' . $e->getMessage();
}
?>

Результатом выполнения данного примера
будет что-то подобное:

Warning: SQLite3::exec(): near "foo": syntax error in example.php on line 4
Поймано исключение: near "bar": syntax error

Yoann

4 years ago

Be sure to note the poorly chosen name and default value.

The following snippet does not throw an exception, despite calling a function with the name "enableExceptions" immediately prior to the bad query.
<?php
$sqlite
= new SQLite3('test.tmp');
$sqlite->enableExceptions();
$sqlite->exec('invalid query');
echo
'code still running since no exception was thrown';
?>

Note that this is still error-prone if the passed value is false. One is likely to read "enableExceptions" and ignore the parameter list since the function name conveys a strong (but incorrect) meaning.

I am trying ways to catch all SQLite3 errors in PHP? I have tried many and they all seem to work. Consider the code below, is it enough to catch all errors? Can someone suggest anything else?

$result = $stmt->execute();
if ($this->db->lastErrorCode()){
    throw new DatabaseError($this->db->lastErrorMsg(), 
                            $this->db->lastErrorCode());
} else {
    return $this->db->changes();
}

  • php
  • sqlite
  • catch-all

Bo Persson's user avatar

Bo Persson

90.8k31 gold badges146 silver badges203 bronze badges

asked Jun 30, 2011 at 18:17

Pwnna's user avatar

PwnnaPwnna

9,18821 gold badges65 silver badges91 bronze badges

1 Answer

I think this is actually enough because there’s an error code when an error is raised of course so this must work.

answered Jan 7, 2012 at 13:33

Cydonia7's user avatar

Cydonia7Cydonia7

3,7442 gold badges23 silver badges32 bronze badges

536 votes

1 answers

Get the solution ↓↓↓

I am trying ways to catch all SQLite3 errors in PHP? I have tried many and they all seem to work. Consider the code below, is it enough to catch all errors? Can someone suggest anything else?

$result = $stmt->execute();
if ($this->db->lastErrorCode()){
    throw new DatabaseError($this->db->lastErrorMsg(), 
                            $this->db->lastErrorCode());
} else {
    return $this->db->changes();
}

Write your answer


97

votes

Answer

Solution:

I think this is actually enough because there’s an error code when an error is raised of course so this must work.


Share solution ↓

Additional Information:

Date the issue was resolved:

Link To Source

Link To Answer
People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content.

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SQLite3 — The SQLite3 class
    • SQLite3::backup — Backup one database to another database
    • SQLite3::busyTimeout — Sets the busy connection handler
    • SQLite3::changes — Returns the number of database rows that were changed (or inserted or
      deleted) by the most recent SQL statement
    • SQLite3::close — Closes the database connection
    • SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createCollation — Registers a PHP function for use as an SQL collating function
    • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
    • SQLite3::enableExceptions — Enable throwing exceptions
    • SQLite3::escapeString — Returns a string that has been properly escaped
    • SQLite3::exec — Executes a result-less query against a given database
    • SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension — Attempts to load an SQLite extension library
    • SQLite3::open — Opens an SQLite database
    • SQLite3::openBlob — Opens a stream resource to read a BLOB
    • SQLite3::prepare — Prepares an SQL statement for execution
    • SQLite3::query — Executes an SQL query
    • SQLite3::querySingle — Executes a query and returns a single result
    • SQLite3::setAuthorizer — Configures a callback to be used as an authorizer to limit what a statement can do
    • SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
  • SQLite3Stmt — The SQLite3Stmt class
    • SQLite3Stmt::bindParam — Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear — Clears all current bound parameters
    • SQLite3Stmt::close — Closes the prepared statement
    • SQLite3Stmt::__construct — Constructs an SQLite3Stmt object
    • SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
    • SQLite3Stmt::getSQL — Get the SQL of the statement
    • SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
    • SQLite3Stmt::readOnly — Returns whether a statement is definitely read only
    • SQLite3Stmt::reset — Resets the prepared statement
  • SQLite3Result — The SQLite3Result class
    • SQLite3Result::columnName — Returns the name of the nth column
    • SQLite3Result::columnType — Returns the type of the nth column
    • SQLite3Result::__construct — Constructs an SQLite3Result
    • SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize — Closes the result set
    • SQLite3Result::numColumns — Returns the number of columns in the result set
    • SQLite3Result::reset — Resets the result set back to the first row

donotspam at alecos dot it

3 years ago


To enable CURL and SQLITE3 on Windows with PHP 7.4 edit httpd.conf and php.ini as below:

httpd.conf:

# load php.ini from chosen directory
PHPIniDir "${SRVROOT}/php"
# load PHP 7.4 on Windows
LoadModule php7_module "${SRVROOT}/php/php7apache2_4.dll"
# load CURL on Windows
LoadFile "${SRVROOT}/php/libssh2.dll"
# load SQLITE3 on Windows
LoadFile "${SRVROOT}/php/libsqlite3.dll"

php.ini:

extension=curl
extension=pdo_sqlite
extension=sqlite3

Now CURL and SQLITE3 are enabled and working fine on Windows on PHP 7.4.


Anonymous

11 years ago


As of PHP 5.4 support for Sqlite2 has been removed. I have a large web app that was built with sqlite2 as the database backend and thus it exploded when I updated PHP. If you're in a similar situation I've written a few wrapper functions that will allow your app to work whilst you convert the code to sqlite3.

Firstly convert your DB to an sqlite3 db.

sqlite OLD.DB .dump | sqlite3 NEW.DB

Then add the following functions to your app:

<?php

function sqlite_open($location,$mode)

{

   
$handle = new SQLite3($location);

    return
$handle;

}

function
sqlite_query($dbhandle,$query)

{

   
$array['dbhandle'] = $dbhandle;

   
$array['query'] = $query;

   
$result = $dbhandle->query($query);

    return
$result;

}

function
sqlite_fetch_array(&$result,$type)

{

   
#Get Columns

   
$i = 0;

    while (
$result->columnName($i))

    {

       
$columns[ ] = $result->columnName($i);

       
$i++;

    }
$resx = $result->fetchArray(SQLITE3_ASSOC);

    return
$resx;

}

?>



They're not perfect by any stretch but they seem to be working ok as a temporary measure while I convert the site.

Hope that helps someone


Anonymous

5 years ago


PHP doesn't seem to support password protection for SQLite3. We can specify password on the db(I think) but you will still be able to open the DB without using a password so it is not working.

alan at chandlerfamily dot org dot uk

13 years ago


PHP 5.3.3 introduced sqlite3::busyTimeout(int milliseconds) which does not currently seem to be documented.

It believe it acts like sqlite::busyTimeout - that is it tells sqlite3 to call an internal busyHandler if SQLITE_BUSY is returned from any call which waits a short period and then retries.  It continues to do this until milliseconds milliseconds have elapsed and then returns the SQLITE_BUSY status.

I don't know whether the default 60 second value is in place if this function is not called.


Запрос базы данных

<?php
//Create a new SQLite3 object from a database file on the server.
$database = new SQLite3('mysqlitedb.db');

//Query the database with SQL
$results = $database->query('SELECT bar FROM foo');

//Iterate through all of the results, var_dumping them onto the page
while ($row = $results->fetchArray()) {
    var_dump($row);
}
?>

См. Также http://www.riptutorial.com/topic/184

Получение только одного результата

В дополнение к использованию операторов LIMIT SQL вы также можете использовать функцию SQLite3 querySingle для извлечения одной строки или первого столбца.

<?php
$database = new SQLite3('mysqlitedb.db');

//Without the optional second parameter set to true, this query would return just
//the first column of the first row of results and be of the same type as columnName
$database->querySingle('SELECT column1Name FROM table WHERE column2Name=1');

//With the optional entire_row parameter, this query would return an array of the
//entire first row of query results.
$database->querySingle('SELECT column1Name, column2Name FROM user WHERE column3Name=1', true);
?>

Это полный пример всех распространенных API-интерфейсов, связанных с SQLite. Цель состоит в том, чтобы заставить вас работать и работать очень быстро. Вы также можете получить исполняемый файл PHP этого урока.

Создание / открытие базы данных

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

$db = new SQLite3('analytics.sqlite', SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);

Создание таблицы

$db->query('CREATE TABLE IF NOT EXISTS "visits" (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    "user_id" INTEGER,
    "url" VARCHAR,
    "time" DATETIME
)');

Вставка образцов данных.

Целесообразно обернуть связанные запросы в транзакции (с ключевыми словами BEGIN и COMMIT ), даже если вам не нужна атомарность. Если вы этого не сделаете, SQLite автоматически обматывает каждый запрос в транзакции, что сильно замедляет все. Если вы новичок в SQLite, вы можете быть удивлены, почему INSERT настолько медленны .

$db->exec('BEGIN');
$db->query('INSERT INTO "visits" ("user_id", "url", "time")
    VALUES (42, "/test", "2017-01-14 10:11:23")');
$db->query('INSERT INTO "visits" ("user_id", "url", "time")
    VALUES (42, "/test2", "2017-01-14 10:11:44")');
$db->exec('COMMIT');

Вставьте потенциально опасные данные с помощью подготовленного оператора. Вы можете сделать это с помощью названных параметров :

$statement = $db->prepare('INSERT INTO "visits" ("user_id", "url", "time")
    VALUES (:uid, :url, :time)');
$statement->bindValue(':uid', 1337);
$statement->bindValue(':url', '/test');
$statement->bindValue(':time', date('Y-m-d H:i:s'));
$statement->execute(); you can reuse the statement with different values

Получение данных

Давайте приступим к сегодняшним посещениям пользователя № 42. Мы снова будем использовать подготовленный оператор, но с пронумерованными параметрами на этот раз, которые являются более краткими:

$statement = $db->prepare('SELECT * FROM "visits" WHERE "user_id" = ? AND "time" >= ?');
$statement->bindValue(1, 42);
$statement->bindValue(2, '2017-01-14');
$result = $statement->execute();

echo "Get the 1st row as an associative array:\n";
print_r($result->fetchArray(SQLITE3_ASSOC));
echo "\n";

echo "Get the next row as a numeric array:\n";
print_r($result->fetchArray(SQLITE3_NUM));
echo "\n";

Примечание. Если строк больше нет, fetchArray () возвращает false . Вы можете воспользоваться этим в while цикл.

Освободите память — это не выполняется автоматически, пока ваш скрипт запущен

$result->finalize();

Shorthands

Вот полезная стенограмма для извлечения одной строки в качестве ассоциативного массива. Второй параметр означает, что мы хотим, чтобы все выбранные столбцы.

Остерегайтесь, эта стенография не поддерживает привязку параметров, но вместо этого вы можете избежать строк. Всегда добавляйте значения в котировки SINGLE! Двойные кавычки используются для имен таблиц и столбцов (аналогично обратным выводам в MySQL).

$query = 'SELECT * FROM "visits" WHERE "url" = \'' .
    SQLite3::escapeString('/test') .
    '\' ORDER BY "id" DESC LIMIT 1';

$lastVisit = $db->querySingle($query, true);

echo "Last visit of '/test':\n";
print_r($lastVisit);
echo "\n";

Еще одно полезное сокращение для получения только одного значения.

$userCount = $db->querySingle('SELECT COUNT(DISTINCT "user_id") FROM "visits"');

echo "User count: $userCount\n";
echo "\n";

Убираться

Наконец, закройте базу данных. Это делается автоматически, когда скрипт заканчивается.

$db->close();

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Php pdo показать ошибки
  • Php pdo вывод ошибок
  • Php вернуть ошибку 500
  • Php mysql посмотреть ошибку
  • Php pdo execute обработка ошибок

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: