PHP/SQLite with multiple SQL statements: $db->Query() works, $this->db_sqlite->query() fails
I am creating a class that handles various SQLite actions. My problem is: When I make a SQL string with multiple statements then it works when using standard PHP => $db->query() ... but it fails when making the same request from a method. It seems that the OO method skips everything after the first ";"-symbol in my SQL statement. Why is that, and how to fix it?
Thanks.
// Fails - line 2 is not inserted, why?
$this->db_sqlite->query("
INSERT INTO foo (name) VALUES('Via class multi-lines 1');
INSERT INTO foo (name) VALUES('Via class multi-lines 2');
");
// Works - both lines are inserted.
$GLOBALS[db]->query("
INSERT INTO foo (name) VALUES('Direct multi-lines 1');
INSERT INTO foo (name) VALUES('Direct multi-lines 2');
");
Full example:
<?php
class db_sqlite {
function __construct() {
$this->connect();
}
function connect() {
$GLOBALS[db] = new SQLiteDatabase("dbsqlite.php.db");
}
function query($sql) {
return $GLOBALS[db]->query($sql);
}
}
class something {
function setup() {
$this->db_sqlite = new db_sqlite();
$this->db_sqlite->query("CREATE TABLE foo ( id INTEGER PRIMARY KEY, name CHAR(255) );");
// Works
$this->db_sqlite->query("INSERT INTO foo (name) VALUES('V开发者_Go百科ia class one line 1');");
$this->db_sqlite->query("INSERT INTO foo (name) VALUES('Via class one line 2');");
// Fails (why?)
$this->db_sqlite->query("
INSERT INTO foo (name) VALUES('Via class multi-lines 1');
INSERT INTO foo (name) VALUES('Via class multi-lines 2');
");
// Works
$GLOBALS[db]->query("
INSERT INTO foo (name) VALUES('Direct multi-lines 1');
INSERT INTO foo (name) VALUES('Direct multi-lines 2');
");
foreach($this->db_sqlite->query("SELECT * FROM foo") as $v) {
echo $v[id] . " - " . $v[name] ."<br>";
}
}
}
$something = new something();
$something->setup();
?>
Output:
1 - Via class one line 1 (correct) 2 - Via class one line 2 (correct) 3 - Via class multi-lines 1 (incorrect) 4 - Direct multi-lines 1 (correct) 5 - Direct multi-lines 2 (correct)The PHP manual page for sqlite_query() says, about using multiple statements in one function call, "...this works only when the result of the function is not used - if it is used, only the first SQL statement would be executed." Since you're returning the result, you're "using" it. That's my guess, anyway.
You can pass an errorMsg holder variable that will be set if any error occur. It could be a good idea to check if sqlite returns anything there:
syntax: query ( string $query [, int $result_type [, string &$error_msg ]] )
$result_type could be SQLITE_BOTH (default)
精彩评论