5.5.15

SQLite3::query

(PHP 5 >= 5.3.0)

SQLite3::queryExécute une requête SQL

Description

public SQLite3Result SQLite3::query ( string $query )

Exécute une requête SQL, et retourne un objet SQLite3Result si la requête retourne des résultats.

Liste de paramètres

query

La requête SQL à exécuter.

Valeurs de retour

Retourne un objet SQLite3Result si la requête retourne des résultats. Sinon, la fonction retourne TRUE si la requête est exécutée avec succès, FALSE si une erreur survient.

Exemples

Exemple #1 Exemple avec SQLite3::query()

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

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

add a note add a note

User Contributed Notes 2 notes

up
6
bohwaz
1 year 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:

<?php

$db
= 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.
up
0
pgarvin76 at gmail dot com
3 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.

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

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