Я использую
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
чтобы получить все строки моей таблицы.
Схема определяется как "id INTEGER PRIMARY KEY, заголовок TEXT, год INTEGER, цена 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 - это кажется слишком медленным.
Полный код теста следующим образом:
<code><?
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, title TEXT, year INTEGER, 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, title, year, price) VALUES (null, "The Wizard of Oz", 1939, 9.95)';
$query[]='INSERT INTO dvds (id, title, year, price) VALUES (null, "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 "
";
}
}
функция main ()
{
if (! $ this-> open_table ()) {
$ This-> add_test_records ();
}
$ This-> dump_test_records ();
}
}
$ test = new sqlite_test ();
$ Тест-> Основной ();