2014年5月14日 星期三

PHP CI框架(CodeIgniter)Mysql資料庫插入篇

最近好懶得寫部落格~呵呵
接下來要教大家怎麼新增資料了
連結資料庫的設定大家參考這篇
在這邊我就不多做範例了

先來看看資料庫建置
一樣建立php資料庫在裡面建立member的資料表

資料表欄位部分
裡面有id,password以及name欄位
記得因為名字會有中文輸入所以要把編碼改成utf8

編寫程式碼
新增application\controllers\insert.php
<?php
if (! defined ( 'BASEPATH' ))
    exit ( 'No direct script access allowed' );
class insert extends CI_Controller {
    public function index() {
        $this->load->view ( 'insert_view' ); // 載入視界並且把資料$data丟進去
    }
    public function insertdata() {
        $data = array ( // $data陣列
                'id' => $this->input->post ( 'id' ), // 用post抓取資料並丟入陣列
                'password' => $this->input->post ( 'password' ),
                'name' => $this->input->post ( 'name' ) 
        );
        $this->load->model ( 'insertmod' ); // 載入model
        $this->insertmod->insertdata ( $data ); // 執行insertmod裡的insertdata副程式內容
        $this->load->view ( 'insert_fin_view', $data ); // 顯示視界並把$data資料丟入
    }
}

新增application\models\insertmod.php
<?php
class insertmod extends CI_Model {
    function __construct() { // 建構值
        parent::__construct (); // 改寫父親
        {
            $this->load->database (); // 載入database資料庫設定
        }
    }
    function insertdata($array) { // insertdata副程式
        $this->db->insert ( 'member', $array ); // 插入資料庫指令
    }
}

application\views下要新增兩個檔案
一個是輸入畫面可以送出資料
另一個則是顯示成功畫面並且顯示顯示的資料
insert_view.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>插入資料範例</title>
</head>
<body>
    <form method="post" action="insert/insertdata" name="from">
        帳號:<input name="id"><br> 
        密碼:<input name="password" type="password"><br> 
        姓名:<input name="name"><br>
        <input value="送出" name="send" type="submit"><br>
    </form>
</body>
</html>
會將form內的值用post的方式打包到insert/insertdata的後台
看一下上面的insert.php應該寫得很清楚

insert_fin_view.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>插入資料範例</title>
</head>
<body>
    帳號:<?= $id;?>
    <br> 密碼:<?= $password;?>
    <br> 姓名:<?= $name;?>
    <br> 資料寫入成功
</body>
</html>

執行結果
接下來請在網址列打上http://127.0.0.1/test/insert
因為是沿用之前範例所以專案名稱一樣是test
網頁輸入畫面部分
第一個畫面是顯示輸入畫面
輸入要新增的資料並按下送出

網頁顯示結果部分
送出後輸入的資料會直接應在網頁裡面
並且顯示資料寫入成功
順道議題"資料寫入成功"這段話不應該這樣寫死在網頁內
應該寫在後台php去判斷是否寫入成功後再傳回true或是false值來顯示結果
本篇因為作者過度懶惰所以就沒寫這部分...請大家原諒我

再來看看資料庫內容
剛剛打的資料真的新增在資料庫裏面囉~~~

有什麼不懂的地方歡迎提問
喜歡這篇文章拜託+1給我鼓勵

2 則留言: