加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

为什么所有数据类型都返回为带有PHP的sqlite3 fetchAll(PDO:FET

发布时间:2020-12-13 17:58:48 所属栏目:PHP教程 来源:网络整理
导读:我在用 $rows = $statement-fetchAll(PDO::FETCH_ASSOC); 得到我桌子的所有行. 模式定义为“id INTEGER PRIMARY KEY,title TEXT,year INTEGER,price REAL” 来自fetchAll结果的一行是 array(4) { [0]= string(1) "1" [1]= string(14) "The Dark Night" [2]=
我在用
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

得到我桌子的所有行.

模式定义为“id INTEGER PRIMARY KEY,title TEXT,year INTEGER,price REAL”

来自fetchAll结果的一行是

array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(14) "The Dark Night"
    [2]=>
    string(4) "2008"
    [3]=>
    string(5) "19.95"
  }

为什么所有数据类型都以字符串形式返回?我希望它们按模式中的定义返回.我理解SQLite的“无类型”特性,但它们确实将有限的数据类型定义为TEXT,INTEGER和REAL.如何使用指定的数据类型返回数据?我不想遍历每一行,并用PHP转换它 – 这似乎太慢了.

完整的测试代码如下:

<?
class sqlite_test {
    function __construct()
    {
        $this->dbase_filename = "test.sqlite";
        $this->init_dbase();

    }

    function init_dbase()
    {
        $this->pdo = new PDO("sqlite:".$this->dbase_filename);
    }

    function open_table()
    {
        $table = "dvds";

        if ( ! ($test_to_see_if_table_exists = $this->pdo->query("SELECT 1 from $table")) ) {
            $schema = "id INTEGER PRIMARY KEY,price REAL";
            $query = "CREATE TABLE $table ($schema)";

            $this->pdo->exec($query);
        }

        return $test_to_see_if_table_exists;
    }

    function add_test_records()
    {
        $query[]='INSERT INTO dvds (id,title,year,price) VALUES (null,"The Dark Night",2008,19.95)';
        $query[]='INSERT INTO dvds (id,"The Wizard of Oz",1939,9.95)';
        $query[]='INSERT INTO dvds (id,"Jaws",1977,6.95)';

        $this->pdo->exec( join(';',$query) );
    }

    function dump_test_records()
    {
        $query = "SELECT * FROM dvds";

        if ($statement = $this->pdo->prepare($query)) {
            $statement->execute();

            $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

            echo "<pre>";
            var_dump($rows);
            echo "</pre>";
        }
    }

    function main()
    {
        if ( ! $this->open_table() ) {
            $this->add_test_records();
        }

        $this->dump_test_records();
    }
}

$test = new sqlite_test();
$test->main();
这与SQLite无关;无论您使用什么来查询数据库,所有记录都将作为字符串集合返回.这只是PHP使用的数据库适配器/驱动程序的本质.

如果希望值为所需类型,则必须手动进行投射.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读