I'm porting over a small php app to use sqlite, and this is the first time that I use sqlite with php and its been a while since i last coded something with php(it was php4 by the time). The trouble i'm having right now is that apparently with sqlite you need to call the sqlite3 object several times since it apparently doesnt establish a permanent connection with the database, so my code right now is filled with
$db = new SQLite3('test.db');
in every single function in the code. is this efficient? i开发者_运维知识库s there a better and cleaner way of doing this?
the other issue that i'm having is if i use sqlite inside say include/functions.php it tries to look for test.db inside this include/ dir when it should be using the app root. how could i fix this efficiently?
You only have to establish a connection again if your $db
variable goes out of scope or is otherwise destroyed. If you create the variable inside a function, it will go out of scope as soon as the function exits, forcing you to recreate the variable/connection in the next function.
As such, in some form or another, you will need to create the variable in a scope that is accessible everywhere a database connection is required. The easiest but ugliest is to create it in the global scope. A better way would be to create a static class that holds the connection and can return the connection handler on request. Another way would be to use dependency injection, basically meaning you pass the connection handle into every function or object where it is needed.
The right answer depends on your existing architecture.
Code
<?php
class SQL {
private $db;
function __construct() {
try {
/*** connect to SQLite database ***/
$db = new PDO("sqlite::memory:");
$db->exec("CREATE TABLE blog (Id INTEGER PRIMARY KEY, text TEXT)");
$this->db = $db;
/*** a little message to say we did it ***/
echo 'database created in memory';
} catch(PDOException $e) {
echo $e->getMessage();
}
}
function add($text) {
$this->db->exec("INSERT INTO blog(text) VALUES ('$text')");
}
function get() {
$res = array();
$result = $this->db->query('SELECT text FROM blog');
foreach ($result as $row) {
$res[] = $row['text'];
}
return $res;
}
}
?>
<?php
$sql = new SQL();
$sql->add('hello');
print_r($sql->get());
?>
<?php
$sql = new SQL();
$sql->add('hello');
$sql->add('world');
print_r($sql->get());
?>
Output:
php sql.inc
database created in memoryArray
(
[0] => hello
)
database created in memoryArray
(
[0] => hello
[1] => world
)
As you can see no sprinkling off $db =
.
P.S: You should use PDO because it is superior to just calling new SQLite3
精彩评论