首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

FleaPHP 資料庫查詢條件 ($conditions) 完整寫法指南:整數、字串、陣列、IN 條件、排序欄位

     編輯:PHP 綜合知識

前言:FleaPHP Table Data Gateway 查詢核心

FleaPHP 的表資料入口類 (Flea_Db_Table 子類) 提供 find($conditions, $sort, $fields)、findAll($conditions, $sort, $fields, $limit, $offset) 等方法。$conditions 參數支援**整數、字串、陣列**三種型別,靈活表達從主鍵查詢到複雜 WHERE 條件。本文系統整理所有寫法並附實戰範例。

一、整數:主鍵精確查詢

// 假設主鍵為 id
$user = $tableUsers->find(123);
// 等同 WHERE `id` = 123

若主鍵非 id,需在 Model 設定 protected $_primary = 'user_id';。

二、字串:原生 SQL WHERE 片段

$conditions = 'id < 3 AND status = "active"';
$users = $tableUsers->find($conditions);
// 直接拼接到 WHERE 後,支援任意複雜 SQL 片段
// 風險:需自行防注入,建議僅用於靜態條件

三、陣列:鍵值對與混合模式

1. 關聯陣列:欄位 = 值 (自動加反引號、參數化)

$conditions = ['username' => 'dualface', 'status' => 'active'];
// WHERE `username` = 'dualface' AND `status` = 'active'

2. 索引陣列:自定義條件片段

$conditions = ['id = 1', 'status = "active"'];
// WHERE id = 1 AND status = "active"

3. 混合模式:鍵值對 + 字串片段

$conditions = [
    'id < 10',           // 字串片段
    'sex' => 'male',     // 鍵值對
    'status' => 'active'
];
// WHERE id < 10 AND `sex` = 'male' AND `status` = 'active'

規則:多條件之間自動以 AND 連接。

四、IN 條件特殊語法

FleaPHP 以 'in()' 為特殊鍵名支援 IN 子句。

1. 主鍵 IN

$conditions = ['in()' => [1, 2, 3]];
// WHERE `id` IN (1, 2, 3)

2. 非主鍵欄位 IN

$conditions = ['in()' => ['username' => ['user1', 'user2', 'user3']]];
// WHERE `username` IN ('user1', 'user2', 'user3')

五、排序 ($sort) 與欄位選取 ($fields)

// 排序:字串 'created_at DESC' 或 'name ASC, id DESC'
$users = $tableUsers->find($conditions, 'created_at DESC');

// 欄位選取:字串或陣列,建議陣列 (自動加反引號)
$fields = ['id', 'username', 'email'];
// 或字串 'id, username, email'
$users = $tableUsers->find($conditions, null, $fields);

六、完整實戰範例

class UserTable extends Flea_Db_Table {
    protected $_name = 'user';
    protected $_primary = 'id';
}

// 查詢:狀態啟用、最近登入、前 20 筆、僅需 id/name/email
$table = new UserTable();
$conditions = [
    'status' => 'active',
    'last_login >' => date('Y-m-d', strtotime('-30 days')), // 支援運算子後綴
    'in()' => ['role_id' => [1,2]] // 角色為管理員或編輯
];
$sort = 'last_login DESC';
$fields = ['id', 'username', 'email', 'role_id'];
$users = $table->findAll($conditions, $sort, $fields, 20, 0);

七、常見誤區與最佳實踐

誤區正確做法
字串條件直接拼接變數改用關聯陣列自動參數化,或手動 quoteInto()
IN 條件用字串拼接使用 ['in()' => [$vals]] 特殊語法
主鍵非 id 卻用整數查詢Model 設定 $_primary 或改用陣列 ['user_id'=>123]
排序欄位用戶可控未驗證白名單驗證 in_array($sort, $allowedSorts)
查詢所有欄位影響效能指定 $fields 僅選需要欄位

結語

FleaPHP $conditions 以**整數主鍵、字串片段、關聯/索引/混合陣列、in() 特殊鍵**四大模式,涵蓋 95% 查詢場景。掌握**自動 AND 連接、反引號保護、參數化防注入、IN 語法、排序欄位白名單**,即能寫出安全高效的查詢代碼。遷移至 Laravel Eloquent、Doctrine QueryBuilder 時,where/whereIn/orderBy/select 對應關係清晰,核心思想不變。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved