PHP 7.1.5 Released


(PHP 5 >= 5.3.0, PHP 7)

SQLite3::queryExecutes an SQL query


public SQLite3Result SQLite3::query ( string $query )

Executes an SQL query, returning an SQLite3Result object if the query returns results.



The SQL query to execute.


Returns an SQLite3Result object if the query returns results. Otherwise, returns TRUE if the query succeeded, FALSE on failure.


Example #1 SQLite3::query() example

= new SQLite3('mysqlitedb.db');

$results $db->query('SELECT bar FROM foo');
while (
$row $results->fetchArray()) {

add a note add a note

User Contributed Notes 3 notes

4 years ago
The recommended way to do a SQLite3 query is to use a statement. For a table creation, a query might be fine (and easier) but for an insert, update or select, you should really use a statement, it's really easier and safer as SQLite will escape your parameters according to their type. SQLite will also use less memory than if you created the whole query by yourself. Example:


= new SQLite3;
$statement = $db->prepare('SELECT * FROM table WHERE id = :id;');
$statement->bindValue(':id', $id);

$result = $statement->execute();


You can also re-use a statement and change its parameters, just do $statement->reset(). Finally don't forget to close a statement when you don't need it anymore as it will free some memory.
paule-panke at example dot com
3 months ago
Check with SQLite3Result::numColumns() for an empty result before calling SQLite3Result::fetchArray().

In contrast to the documentation SQLite3::query() always returns a SQLite3Result instance, not only for queries returning rows (SELECT, EXPLAIN). Each time SQLite3Result::fetchArray() is called on a result from a result-less query internally the query is executed again, which will most probably break your application.
For a framwork or API it's not possible to know in before whether or not a query will return rows (SQLite3 supports multi-statement queries). Therefore the argument "Don't execute query('CREATE ...')" is not valid.
pgarvin76 at gmail dot com
6 years ago
The notes for the return value is a little misleading to me. It states that if the query does not "return results" TRUE or FALSE is returned instead. If there is a return value for this method in your PHP code this method always returns an SQLite3Result object, even if you accidentally run an INSERT, UPDATE, DELETE, CREATE TABLE, etc query through it. The only time it returns a TRUE or FALSE is if there is no return value.

= $dbh->query('CREATE TABLE ...');
if (!(
$result instanceof Sqlite3Result)) {
"Query successful."; // This will never echo.
} else {
$result->fetchArray(); // This will throw an error.

if (
$dbh->query('CREATE TABLE ...')) {
"Query successful."; // Works
} else {
"Query failed."; // Will also work
Use exec() if you are not executing a SELECT query.
To Top