在 CodeIgniter 中,使用數(shù)據(jù)庫是非常頻繁的事情。你可以使用框架自帶的數(shù)據(jù)庫類,就能便捷地進(jìn)行數(shù)據(jù)庫操作。
初始化數(shù)據(jù)庫類
依據(jù)你的數(shù)據(jù)庫配置載入并初始化數(shù)據(jù)庫類:
$this->load->database();
被載入之后你可以在任何地方使用它。
以對(duì)象形式返回查詢結(jié)果
$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->email;
}
echo 'Total Results: ' . $query->num_rows();
上面的result()函數(shù)返回一個(gè)對(duì)象的數(shù)組。例如:$row->title
以數(shù)組形式返回查詢結(jié)果
$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['email'];
}
上面的result_array()函數(shù)返回一個(gè)帶下標(biāo)的數(shù)組。例如:$row['title']
返回一條數(shù)據(jù)
對(duì)象形式:
$query = $this->db->query('SELECT name FROM my_table LIMIT 1');
$row = $query->row();
echo $row->name;
上面的row()函數(shù)返回一個(gè) 對(duì)象。例如:$row->name
數(shù)組形式:
$query = $this->db->query('SELECT name FROM my_table LIMIT 1');
$row = $query->row_array();
echo $row['name'];
上面的row_array()函數(shù)返回一個(gè) 數(shù)組。例如:$row['name']
插入(insert)數(shù)據(jù)
$sql = "INSERT INTO mytable (title, name)
VALUES (".$this->db->escape($title).", ".$this->db->escape($name).")";
$this->db->query($sql);
echo $this->db->affected_rows();
快捷插入方式:
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}')
數(shù)據(jù)庫配置
CodeIgniter 有一個(gè)配置文件讓你存放數(shù)據(jù)庫連接值(username:用戶名,password:密碼,database name:數(shù)據(jù)庫名,等等..). 配置文件位于以下路徑:application/config/database.php
配件文件存放在一個(gè)如下格式的一個(gè)多維數(shù)組里:
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
使用多維數(shù)組的原因是為了讓你隨意的存儲(chǔ)多個(gè)連接值的設(shè)置。舉例:如果你運(yùn)行多個(gè)環(huán)境(development:開發(fā)、production:制作、test:測(cè)試 等等..),你能為每個(gè)環(huán)境建立獨(dú)立的連接組,并在組直接進(jìn)行切換。舉例,設(shè)置一個(gè)"test"環(huán)境,你可以這樣做:
$db['test']['hostname'] = "localhost";
$db['test']['username'] = "root";
$db['test']['password'] = "";
$db['test']['database'] = "database_name";
$db['test']['dbdriver'] = "mysql";
$db['test']['dbprefix'] = "";
$db['test']['pconnect'] = TRUE;
$db['test']['db_debug'] = FALSE;
$db['test']['cache_on'] = FALSE;
$db['test']['cachedir'] = "";
$db['test']['char_set'] = "utf8";
$db['test']['dbcollat'] = "utf8_general_ci";
那么,告訴系統(tǒng)使用"test"組,你可以設(shè)置位于配置文件中的變量:
$active_group = "test";
注意: "test"的名字是任意的,這可以讓你自由設(shè)置,我們的主要連接默認(rèn)使用"default"這個(gè)名字,當(dāng)然,您可以基于您的項(xiàng)目為它起一個(gè)更有意義的名字。