【问题标题】:PHP/SQLite with multiple SQL statements: $db->Query() works, $this->db_sqlite->query() fails具有多个 SQL 语句的 PHP/SQLite:$db->Query() 有效,$this->db_sqlite->query() 失败
【发布时间】:2009-11-05 20:36:41
【问题描述】:

我正在创建一个处理各种 SQLite 操作的类。我的问题是:当我用多个语句创建一个 SQL 字符串时,它在使用标准 PHP => $db->query() 时可以工作......但在从一个方法发出相同请求时它会失败。似乎 OO 方法跳过了我的 SQL 语句中第一个“;”符号之后的所有内容。为什么会这样,如何解决?

谢谢。

// 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');
");

完整示例:

<?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('Via 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();
?>

输出:
1 - 通过第一类线路 1(正确)
2 - 通过第一类线路 2(正确) 3 - 通过类多行 1(不正确)
4 - 直接多行 1(正确)
5 - 直接多行 2(正确)

【问题讨论】:

    标签: php sql sqlite oop


    【解决方案1】:

    sqlite_query() 的 PHP 手册页说,关于在一个函数调用中使用多个语句,“......这仅在不使用函数的结果时有效 - 如果使用它,只有第一个 SQL 语句会被处决。”由于您要返回结果,因此您正在“使用”它。无论如何,这是我的猜测。

    【讨论】:

    • 感谢您的参考。这将触发多个查询(不返回结果): $GLOBALS[db]->queryExec($sql) ... 它也可以作为类方法。
    【解决方案2】:

    您可以传递一个 errorMsg 持有者变量,如果发生任何错误,该变量将被设置。检查 sqlite 是否在那里返回任何内容可能是个好主意:

    语法: 查询(字符串 $query [, int $result_type [, string &$error_msg ]])

    $result_type 可以是 SQLITE_BOTH(默认)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-29
      • 2011-12-15
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-01
      相关资源
      最近更新 更多