$db['default']['hostname'] = "your-db-host"; $db['default']['username'] = "your-username"; $db['default']['password'] = "your-password"; $db['default']['database'] = "your-db-name"; $db['default']['dbdriver'] = "mysql";
CREATE TABLE IF NOT EXISTS `users` ( `id` INT(8) NOT NULL AUTO_INCREMENT, `name` VARCHAR(30) CHARACTER SET utf8 DEFAULT NULL, `age` VARCHAR(3) CHARACTER SET utf8 DEFAULT NULL, `sex` VARCHAR(2) CHARACTER SET utf8 DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_estonian_ci AUTO_INCREMENT=14 ;
4.实现MVC
1)实现M--取数据
CI的models下新建一个文件mtest.php
<?php class Mtest extends CI_Model{ function Mtest(){ parent::__construct(); } function get_last_ten_entries() { $this->load->database(); mysql_query("SET NAMES GBK"); //防止中文乱码 $query = $this->db->get('users', 10); return $query->result(); } } ?>
parent::__construct();不可少
$this->load->database();一定不能少不然会报错
也可以实现“自动连接” 功能,将在每个一页面加载时被自动实例化数据库类。要启用“自动连接”,可在如下文件中的 library 数组里添加 database:
application/config/autoload.php
不然就要像这里一样写在每个页面上。
也可以用
$query = $this->db->query('select * from users');
<?php class Test extends CI_Controller { function Test(){ parent::__construct(); } function index(){ $this->load->helper('form'); $data['title'] = "首页"; $data['headline'] = "录入用户信息"; //多维数组 $data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands'); //$this->load->vars($data); $this->load->model('mtest'); $data['query1'] = $this->mtest->get_last_ten_entries(); $this->load->view('users',$data); //$this->load->view('newfile'); //$this->load->view('a/newfile'); } } ?>
$this->load->model('mtest');
$data['query1'] = $this->mtest->get_last_ten_entries();
$this->load->view('users',$data);
2)实现V--页面显示
CI的views下新建一个文件user.php
<head> <title><? echo $title;?></title> </head> <body> <ul> <?php foreach($todo_list as $item):?> <li><?php echo $item;?></li> <?php endforeach;?> </ul> <ul> <? echo count($query1); foreach ($query1 as $v1) { foreach ($v1 as $v2) { echo "$v2\n"; } } for ($row=0;$row<count($query1);$row++) { echo $query1[$row]->name."</br>"; } ?> <?php foreach($query1 as $v):?> <li><?php echo $v->name;?></li> <?php endforeach;?> </ul> </h2><?php echo $headline; ?></h2> </body> </html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
mysql_query("SET NAMES GBK"); //防止中文乱码 mysql_query("set names utf8;");//在mysql_select_db("");后加入. //防止中文乱码 要看你的数据库字符集
$db['default']['char_set'] = 'utf8'; //utf8. 数据库字符集也是utf8 $db['default']['dbcollat'] = 'utf8_general_ci';
希望本文所述对大家CI框架程序设计的学习有所帮助。