データの取り出しを簡単にできるし、まじびっくり!!
以下メモ
・データベースについては、application/modelsに(データベース名)_model.phpに以下のコードを書く
class News_model extends CI_Model { public function __construct() { $this->load->database(); } public function get_news ($slug = false) { if ($slug === FALSE) { $query = $this->db->get('news'); return $query->result_array(); } $query = $this->db->get_where('news', array('slug' => $slug)); return $query->row_array(); } }
コントローラーにおける->dbはデータベースにつなげるだけだから、(テーブル名)_modelにしたからってそのテーブルだけしかつなげないということではない
・コントローラー(モデルとビューの橋渡し)はapplication/controllersに(テーブル名 || urlにしたい文字列).phpに以下のコードを書く
・functoinの名前は(クラス名)/(function名)のurlにアクセスされたときの処理
class News extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('news_model'); } public function index() { $data['news'] = $this->news_model->get_news(); $this->load->view('news_index', $data); } public function view($slug) { $data['news'] = $this->news_model->get_news($slug); } }
・ビュー。コントローラーで処理されたデータを表示する
こんにちは!
viewで変数にアクセスするには、$dataの連想配列のキーになる
<追記>
複雑なselectを書けたいときに参考になる
http://ellislab.com/codeigniter/user-guide/database/active_record.html#select
複数のメソッドをつなげる
こんな感じに
$this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20);
$query = $this->db->get();
詳細はMethod Chainingを参照
rowをカウントする
$this->db->where('id', 2); $this->db->count_all_results();
No comments:
Post a Comment