延續之前的帳號申請練習
之前那篇只有做頁面的轉換而已,並沒有實質的功能:因為以下兩個功能還沒有實做
$this->load->model('account_model');
$this->account_model->apply_account();
這篇將介紹如何實做資料庫和網頁的連結
管理資料庫
- 瀏覽器輸入
localhost/phpMyAdmin/
登入帳號 root 登入密碼 pwd
pwd 是在此篇中,在安裝AppServ的MySQL Server Configuration 所說要記住的密碼 (此後用pwd代稱)建立一個名叫
account
的 database(資料庫)
-
初始化 database 的 table
依照自己的需求初始化table
此例中,選擇資料庫account
,選擇SQL執行初始化的code
建一張名為user的table,有account和country兩個char欄位CREATE TABLE `user` ( `account` VARCHAR( 250 ) NOT NULL , `country` VARCHAR( 250 ) NOT NULL ) ENGINE = MYISAM ;
account/application/config/database.php
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'pwd';
$db['default']['database'] = 'account'; //前面建立的database名稱
account/application/models/account_model.php
<?php
class Account_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function apply_account()
{
$this->load->helper('url');
$data = array(
'account' => $this->input->post('account'),
'country' => $this->input->post('country'),
);
return $this->db->insert('user', $data);
}
}
從views中對應的account、country 使用 input->post 取值分別放到 account、country 中
然後利用 array data , insert到 user 這張 table
注意是user
不是 account( account是在 $this->load->database();
載入的 database
)
// 要做table查詢的話,可以在 module 中用 $query = $this->db->get('user');
,
// 配合在views中使用 foreach
達到。
demo
在之前 mod_rewrite設定後,在瀏覽器打 localhost/account/account
就可以看到 demo 啦
現在輸入資料後
到 localhost/phpMyAdmin/
裡面 account 資料庫的 user table 就可以看到網頁剛輸入的資料