想必大家跟我一樣,不喜歡死板板的頁面(誰喜歡啊?)
今天終於要進入「活頁」的第一步了:
撈出資料庫的東西,秀在頁面上!
忍不住要碎念一下,導覽手冊的標題⋯⋯大陸翻譯的頗怪異,什麼「讀取新聞條目」,但是功能說明滿貼近的。台灣翻譯——「新聞模組介紹」,事實上,只有撈出新聞資料,這到底⋯⋯怎麼翻的。
#前言
請原諒個人小龜毛的個性,無法大放厥詞的去解釋自己不懂的東西,且前面章節的「靜態頁面」中routes.php未做設定,考量一致性、避免設定錯誤找不到網頁,所以這篇也略過routes.php的部分。
#進入正題
我假設你「已經知道」且「已經有」MySQL資料庫的環境,如果你問我什麼是MySQL?我會建議你先找PHP應用的基本文章再來學Framework呦,因為地基打不穩,要怎麼往上蓋樓呢?framework就是蓋樓的概念唷!
附註:會搜尋CI這名詞,大多數應該都知道吧~
我們要建立的是User Guide上的「指導手冊 − 新聞模組介紹」部分,功能就是從資料庫撈出資料並顯示在畫面上。
功能說明:
-顯示全部新聞
-顯示單篇新聞
本篇大約步驟:
-建立資料表
-建立資料
-編寫程式
寄實體信需要提供「地址」、電子信需要「電子信箱」,當然,要撈資料當然也需要告訴程式「資料庫在哪」、「是哪個資料庫」嘛!設定資料庫的方法有兩種(斯斯?),一是設定在設定檔,另一種是手動載入,這與程式執行需求有關係~
設定檔載入
到application/config/database.php中修改下列區段:
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'myusername';
$db['default']['password'] = 'mypassword';
$db['default']['database'] = 'mydatabase';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
手動載入
$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = "mydatabase";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$this->load->database($config);
以往「資料庫連線」這個問題,自己刻就是建立一個class之後載入,但~CI有很貼心的自動載入功能,能讓程式一開始的時候就幫你載入。在CI的自動載入檔案(application/config/autoload.php)中找到libraries,加上database的部分。如下:
$autoload['libraries'] = array('database');
我這個網站只有特定頁面才用耶,我不想全部都載入,怎麼辦?當然是手動載入存在才會衍生到自動載入的,把下面的代碼加到有載入需求的程式就可以囉!
$this->load->database();
把這段來自使用手冊的語法貼入資料庫執行,資料表就建立完成了,此部分本篇開頭所述,假設你已對資料庫有所瞭解,故不詳述其語法內容。
CREATE TABLE news (
id int(11) NOT NULL AUTO_INCREMENT,
title varchar(128) NOT NULL,
slug varchar(128) NOT NULL,
text text NOT NULL,
PRIMARY KEY (id),
KEY slug (slug)
);
請在你的MySQL上執行下面語法,執行完會多兩筆資料。
INSERT INTO `news` (`id`, `title`, `slug`, `text`)
VALUES
(1,'Write Like You Talk','first','Heres a simple trick for getting more people to read what you write: write in spoken language. Something comes over most people when they start writing. They write in a different language than they'),
(2,'A decade at google','second','One of the key challenges you face in an industrial research lab is how to choose your projects. You want your projects to be interesting research but also contribute to your company. As a junior researcher, you?re typically in the situation of choosing a project to join, while later in your career you are expected to come up with and lead your own projects. Regardless of your age, you have to make an educated decision.');
辛苦大家設定、試玩完成,下一篇就會進入程式的應用了!