本文實例講述了CodeIgniter針對數據庫的連接、配置及使用方法。分享給大家供大家參考,具體如下:
1. 數據庫:
create database test;create table users(id int not null,name varchar(10),pwd varchar(10),email varchar(20))insert into users values(1,'shunping','shunping','[email protected]');insert into users values(2,'shunping2','shunping2','[email protected]');
2. 我用的是Postgreql
在/CodeIgniter/system/application/config/database.php文件中配置數據庫參數:
$active_group = "default";$db['default']['hostname'] = "localhost";$db['default']['username'] = "postgres";$db['default']['password'] = "admin";$db['default']['database'] = "test";$db['default']['dbdriver'] = "postgre";$db['default']['dbprefix'] = "";$db['default']['active_r'] = TRUE;$db['default']['pconnect'] = FALSE;$db['default']['db_debug'] = TRUE;$db['default']['cache_on'] = FALSE;$db['default']['cachedir'] = "";$db['default']['port'] = "5432";
在/CodeIgniter/system/application/controllers目錄下測試文件db1.php內容如下:
<?phpclass Db1 extends Controller{ function index(){ $this->load->database(); $query=$this->db->query("select name,pwd,email from users"); foreach ($query->result() as $row) {//返回對象數組 echo $row->name; echo $row->pwd; echo $row->email."<br>"; } echo "Total Result==".$query->num_rows(); }}?>
打開瀏覽器敲入地址:
http://localhost:8888/index.php/MyController/db1
ok搞定!
我想大家肯定也遇到過連不上數據庫的問題,我花費了好些精力才解決這個問題,現在告訴大家,希望對大家學習CodeIgniter這個優秀的PHP框架有所幫助。