PHP Conference Japan 2024

SQLite3Result 類別

(PHP 5 >= 5.3.0,PHP 7,PHP 8)

簡介

處理 SQLite 3 擴充套件結果集的類別。

類別概要

class SQLite3Result {
/* 方法 */
private __construct()
公開 columnName(int $column): string|false
公開 columnType(int $column): int|false
公開 finalize(): true
公開 numColumns(): int
公開 reset(): bool
}

目錄

新增註釋

使用者貢獻的註釋 5 則註釋

jonscully at gmail dot com
15 年前
由於 SQLite3Result::numRows 無法使用,請使用

<?php
if ($res->numColumns() && $res->columnType(0) != SQLITE3_NULL) {
// 有資料列
} else {
// 零資料列
}
?>

因為當沒有資料列時
* SQLite3Result::fetchArray 將會傳回 '1'
* SQLite3Result::numColumns 將會傳回 '1'
第 0 欄的欄位類型將會是 SQLITE3_NULL
sameers dot public at gmail dot com
10 年前
根據 https://php.dev.org.tw/manual/en/sqlite3result.columntype.php, 以及我個人的經驗,columnType() 只會回傳 SQLITE3_NULL。因此,註解中建議用來判斷欄位是否為 NULL 的測試方法是錯誤的。

正確的做法似乎應該是測試 if (($result->fetchArray())[0] == null)。
jan at bootfinder dot co dot uk
10 年前
我使用以下程式碼來取得 num_rows (列數)

<?php
...
$nrows = 0;
$result->reset();
while (
$result->fetchArray())
$nrows++;
$result->reset();
return
$nrows;
...
?>
atesin () 6m4i1 ! com
3 年前
回覆 jan at bootfinder dot co dot uk (留言 #115891) 關於取得 num_rows 的部分…

這樣如何 (未測試)…?

<?php // 如果需要,在前後執行清除動作

for ( $nrows = 0; is_array($result->fetchArray()); ++$nrows );
return
$nrows;

?>
alan71-at-free-fr
13 年前
以下程式碼片段或許能幫助你撰寫同樣缺少的 fetchObject 函式

<?php

函式 fetchObject($sqlite3result, $objectType = NULL) {
$array = $sqlite3result->fetchArray();

if(
is_null($objectType)) {
$object = new stdClass();
} else {
// 不會呼叫此類別的建構子
$object = unserialize(sprintf('O:%d:"%s":0:{}', strlen($objectType), $objectType));
}

$reflector = new ReflectionObject($object);
for(
$i = 0; $i < $sqlite3result->numColumns(); $i++) {
$name = $sqlite3result->columnName($i);
$value = $array[$name];

try {
$attribute = $reflector->getProperty($name);

$attribute->setAccessible(TRUE);
$attribute->setValue($object, $value);
} catch (
ReflectionException $e) {
$object->$name = $value;
}
}

return
$object;
}

?>

大量參考 Bergmann 的 Object Freezer
https://github.com/sebastianbergmann/php-object-freezer/blob/master/Object/Freezer.php
To Top