CI,从数据库读取数据

1、准备数据库,(用户,密码,数据库服务的地址)

2、CI链接数据库,配置database.php(配置文件)       //application/config/database.php

3、准备MVC,也就是约定或定义 访问的url http://192..../ci/index.php/user/getinfo

4、开始写代码

5、自我测试

///////////////////////////////////////////////////////////////////////////////

controllers\user.php

<?php
defined('BASEPATH') or die('bad Access');


class user extends CI_Controller{
    
    function __construct(){
        
        parent::__construct();  //因为 父类构造函数 在子类被重载, 所以需要在这里必须调用父类的构造函数
        
        $this->load->helper('url');
        
        }
    
    
    
    
    function getinfo(){
        
        $this->load->model('User_m');   //控制器 加载 模型, 并创建了模型对象, 这个对象名就是模型名
        //$this->load->model('User_m','userm'); //第二种加载方式, 可以给一个别名用于接下来的对象名
        $r_data = $this->User_m->getinfoM(); //刚创建的模型对象 在调用它的方法
        
        
        $d['infolist']=$r_data;  //创建一个数组,便于将数据发送给视图   //$d[模块变量]
        
        
        
        $this->load->helper('myfun'); //这里是, 在加载第三方函数库
        $d['myf'] = abcAdd(5,6);   //这个abcAdd 是函数库里的一个函数 如混编时代那样 直接使用即可
        
        
        
        $this->load->library('myclass');   //这里是, 在加载第三方类库
        //没有 $this->load->library('myclass','mcc');  //加载第三方类库 没有 第二种加载方式(给别名),
        
        $d['myc'] =$this->myclass->add(5,8);  //add 是类库里的一个方法 如混编时代那样 直接使用即可
                                              // $this->myclass 如同模型类一样被生成的。
        
        
        
        $this->load->view('getinfo_v',$d);  //调用视图, 并同时将数据发送给视图
        
        
    }
    
   function get2(){
       
       
       
       $this->load->view('get2');
       
       
       }
    
}    

 

 

/////////////////////////////////////////////////////////////////////////////////

views\getinfo_v.php

<?php
defined('BASEPATH') or die('bad Access');

?>

<html>
<head>
    <meta charset="utf-8" />
    </head>    
    <style>
      td{border: 1px solid #ccc;}    
    </style>
    <body>
        
        <h1>hello</h1>
        <img src="<?php echo base_url('img/abd.jpg') ?>">
        <hr>
        <?php 
         
         echo '<table>';
         
         foreach( $infolist as $row ){
         
         echo '<tr><td>'.implode('</td><td>',$row) .'</td></tr>';     
             
             
         }
          echo '</table>';
          
        echo '<hr>'.abcAdd(10,6).'<br>'.$myc;
        
        ?>
        
        
        
        </body>
    
</html>

 

 

/////////////////////////////////////////////////////////

models\User_m.php

<?php
defined('BASEPATH') or die('bad Access');

class User_m extends CI_Model{
    
   function getinfoM(){
       
        $this->load->database();    //连接数据库
       
        $sql="select * from student"; //组建sql语句
          
        $res = $this->db->query($sql); //向数据库发送sql语句, 并接收到数据库返回来的 数据集
       
        return $res->result_array();   //result_array 将 有效数据集 转为 二维数组结构的数据
       
       
       
       }    
    
    
}

 

posted @ 2016-09-21 10:05  CoKeny  阅读(647)  评论(0编辑  收藏  举报