Active Record簡化數據庫操作

Active Record簡化數據庫操作

1、編輯system/application/config/database.php配置文件,將下列參數填好。
$active_group = "default";
$db['default']['hostname'] = "";
$db['default']['username'] = "";
$db['default']['password'] = "";
$db['default']['database'] = "";
$db['default']['dbdriver'] = "";
說明:
hostname: 你的數據庫的位置, 舉例來說, 'localhost' 或 IP 地址 
username和password: 使用者名稱和密碼必須有充分的權限,允許你的網站存取數據庫中的數據。 
database: 你的數據庫的名字, 舉例來說, 'websits' 
dbdriver: 你正在使用的數據庫的類型 - CI可受的有選項有MySQL、MySQLi、 Postgre SQL、ODBC和MS SQL 

2、數據庫操作
AR是一個“設計模式”。它的核心是把你的數據庫和PHP對象建立一個對應關係。每次當你執行一個QUERY語句。每一張數據庫裏的表是一個類,每一行是一個對象。所有你需要做的只是創建它,修改它或者刪除它。

(1)連接數據庫
$this->load->database();

(2)執行查詢
$query = $this->db->get('sites');  //select * From sites

$this->db->select('url','name','clientid');    // Select url,name,clientid from sites order by name desc
$this->db->orderby("name", "desc");
$query = $this->db->get('sites');


$this->db->select('url','name','clientid','people.surname AS client');  
$this->db->where('clientid', '3');
$this->db->limit(5);
$this->db->from('sites');
$this->db->join('people', 'sites.clientid = people.id');
$this->db->orderby("name", "desc");
$query = $this->db->get();
// 循環顯示
foreach ($query->result() as $row)
{
  print $row->url;
  print $row->name;
  print $row->client;
}

(3)添加新記錄
方法1:
$data = array(
                'url' => 'www.mynewclient.com',
                'name' => 'BigCo Inc',
                'clientid' => '33',
                'type' => 'dynamic'
            );
$this->db->insert('sites', $data);
方法2:
$this->db->set('url', 'www.mynewclinet.com');
$this->db->set('name', 'BigCo Inc');
$this->db->set('clientid', '33');
$this->db->set('type', 'dynamic');
$this->db->insert('sites');

(3)更新記錄
$this->db->where('id', '1');
$this->db->update('sites', $data);

(4)刪除記錄
$this->db->where('id', '2');
$this->db->delete('sites');
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章