CodeIgniter 小筆記 ================= # 查詢 ## 1.連接資料庫 1.1 到config>database.php 填入資料庫的帳號、密碼 1.2 到config>utoload.php 加入`$autoload['libraries'] = array('database');` ## 2.產生查詢結果 2.1 在controller裡建一個php檔 2.2 加入`class Controller_name extends CI_Controller { //code here }`,`Controller_name`和檔案同名 2.3 加入一個function ex.`public function index(){ //code here }` 2.4 把資料抓出來 2.4.1 多筆資料 ``` $q = $this->db->from("table_name")->get(); $data['chars'] = $q->result(); $this->load->view('view_name', $data); ``` 2.4.2 單筆資料 class記得要代變數 ex. `public function char($id=0)` ``` $q = $this->db->from("table_name")->where('id',$id)->get(); //'id'是key,$id是value $res = $q->result(); if(empty($res)){ //檢查有沒有抓到資料 show_404(); return; } $data['char'] = $res[0]; //取陣列第一項 $this->load->view('charView', $data); ``` ## 3. 到 view把東西echo出來 3.1 多筆資料 ex. ``` <ul> <?php foreach ($chars as $c) { ?> <li><?=$c->column_name ?></li> <?php } ?> </ul> ``` 3.2 單筆資料 直接`<?=$c->column_name ?>`即可 --- # 連結 ## 1.更改連結相關的config 1.1 到config>config.php 改`$config['base_url']`的路徑 1.2 到config>autoload.php 加入`$autoload['helper'] = array('url');` ## 2.在view的地方設超連結 ex. ``` <a href="<?= base_url("/your_controller") ?>" ``` php中的字串以`.`連接,所以也可以 ``` <a href="<?= base_url("/your_controller". $c->id) ?>" ```