1 回答

TA貢獻1877條經驗 獲得超1個贊
您存儲對象的時間不應mysqli_result超過獲取數據所需的時間。它僅用作從 MySQL 獲取數據的臨時對象。而是緩存值。
if (isset($dbcache[$query])) {
$this->result = $dbcache[$query];
} else {
$dbcache[$query] = $this->result = $dbh->query($query)->fetch_all(MYSQLI_ASSOC);
}
但是,我對這種方法對于準備好的語句的有用性持謹慎態度。您可能希望將鍵設為查詢和參數的組合。例如:
$key = serialize([$query, ...$params]);
if (isset($dbcache[$key])) {
$this->result = $dbcache[$key];
} else {
//prepare bind execute
$stmt = $dbh->prepare($query);
if ($params) {
$stmt->bind_param(str_repeat("s", count($params)), ...$params);
}
$stmt->execute();
// Fetch results into multidimensional array
$dbcache[$key] = $this->result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}
您確實應該避免在應用程序代碼中使用 mysqli 函數。如果您正在構建某種抽象層,那么您應該只將數據返回到應用程序并僅在內部使用 mysqli。使用我推薦的方法,您將像普通數組一樣訪問數據;沒有更多的fetch_object()方法了。當然,這需要您更改應用程序代碼,但這樣做是個好主意。我還強烈建議開始使用 PDO。
- 1 回答
- 0 關注
- 104 瀏覽
添加回答
舉報