初心者にもわかるCodeIgniter 其の四【DBとModelの利用】
 
								
									この記事は最終更新日から1年以上が経過しています。
								
															DBの接続
DBをあるものとして話を進めていきます。
application/config/database.php を編集
<?php $db['default'] = array( 'hostname' => 'localhost', 'username' => 'hogehoge', 'password' => '123456789', 'database' => 'dbname', ); ?>
編集箇所は上記のみで動作します。
Modelの作成
Modelの中身は状況に応じて書き足すこともありますが、僕は基礎として以下のものを必ず設置してます。
要するにBootstrap的な役割をするModelですね。
application/model/All.php を作成
<?php
class All extends CI_Model {
	function __construct(){
		parent::__construct();
		$this->load->database();
	}
	//全行取得
	public function getAll($table, $target_array=NULL, $order=NULL, $limit=NULL, $start=0) {
		$this->db->from($table);
		if($target_array){
			foreach($target_array as $key => $val){
				$this->db->where($key, $val);
			}
		}
		if ($order)
			$this->db->order_by($order);
		if ($limit) 
			$this->db->limit($limit,$start);
		$query = $this->db->get();
		return $query->result('array');
	}
	
	//1行取得
	public function getRow($table, $target_array, $order=NULL, $return=NULL) {
		$this->db->from($table);
		foreach($target_array as $key => $val){
			$this->db->where($key, $val);
		}
		$this->db->limit(1);
		if ($order)
			$this->db->order_by($order);
		$query = $this->db->get();
		if ($query->num_rows() > 0){
			if ($return){
				$row = $query->row_array();
				return $row[$return];
			}else{
				return $query->row_array();
			}
		}
	}	
	//件数取得
	public function getCC($table, $target_array) {
		$this->db->from($table);
		if($target_array){
			foreach($target_array as $key => $val){
				$this->db->where($key, $val);
			}
		}
		return $this->db->count_all_results();
	}		
	
	//update
	public function Update($table, $target_array, $data, $limit=0) {
		foreach($data as $key => $value){
			$this->db->set($key, $value);
		}
		foreach($target_array as $key2 => $val){
			$this->db->where($key2, $val);
		}
		if($limit > 0){
			$this->db->limit($limit);
		}
		$this->db->update($table);
	}
	//delete
	public function Delete($table, $target_array, $where_method='and', $limit=0) {
		foreach($target_array as $key => $val){
			if ($where_method == 'and')
				$this->db->where($key, $val);
			if ($where_method == 'or')
				$this->db->or_where($key, $val);
		}
		if($limit > 0){
			$this->db->limit($limit);
		}
		$this->db->delete($table);
	}
	//insert
	public function Insert($table, $data) {
		foreach($data as $key => $value){
			$this->db->set($key, $value);
		}
		$this->db->insert($table);
		return $this->db->insert_id();
	}
}
?>
これだけで大概のものは取得できます。
Modelの利用
では、modelを呼び出してデータを呼び出してみましょう。
まず、DBに情報を挿入します。
次々回あたりでログインの仕組みを作るので、userテーブルを作ります。
CREATE TABLE `user` ( `user_id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, `mail` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `user` (`user_id`, `name`, `mail`, `password`) VALUES (1, 'ManA', 'mana@dummy.jp', 'XXXXXX'), (2, 'ManB', 'manb@dummy.jp', 'XXXXXX'); ALTER TABLE `user` ADD PRIMARY KEY (`user_id`); ALTER TABLE `user` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
続いてModelの読み込みと関数の利用です。
application/controllers/Top.php を編集
現在表示中のページに以下を追加
$this->load->model(array('All'));
$list = $this->All->getAll('user');
print_r($list);
これでTable user の中身が表示されます。
簡単ですね。
Modelで読み込んだものをViewで表示
呼び出したものをcontrollers上で表示しても意味がありません。
Viewに渡して表示しなければ。
そこで、TOPページに情報を渡して、表示するまでやってみましょう。
application/controllers/Top.php を編集
public function index()
{
	$this->load->model(array('All'));
	$data = $this->data;
	$list = $this->All->getAll('user');
	$data['list'] = $list;
	$this->load->view('index',$data);
}
application/views/index.php に以下を追加
<table class="table table-striped"> <thead> <th>ID</th> <th>name</th> <th>mail</th> </thead> <tbody> <?php foreach($list as $val): ?> <tr> <td><?php echo $val['user_id'] ?></td> <td><?php echo $val['name'] ?></td> <td><?php echo $val['mail'] ?></td> <tr> <?php endforeach; ?> </tbody> </table>
以上です。
これである程度のものが呼び出して表示することが可能になりました。
見本はこちら。
参考ページ:http://sample.xn--pbku02iq0izkz.net/
次回はユーザーの登録とログインの機能を作ります。
 
						