ThinkPHP链接数据库

来源:互联网 发布:java转义html特殊字符 编辑:程序博客网 时间:2024/05/19 02:16

在配置文件中做如下配置便可链接数据库

<?phpreturn array(   //'配置项'=>'配置值'    'DB_TYPE'               =>  'mysql',     // 数据库类型    'DB_HOST'               =>  'localhost', // 服务器地址    'DB_NAME'               =>  'shop',          // 数据库名    'DB_USER'               =>  'root',      // 用户名    'DB_PWD'                =>  '123',          // 密码    'DB_PORT'               =>  '3306',        // 端口    'DB_PREFIX'             =>  'sw_',    // 数据库表前缀);

创建Model模型

’Home/Model’文件夹剪切到Application文件夹下,让HomeAdmin共同使用。

我的数据库表明是goods,首先创建一个与数据库名相同的模型类

GoodsModel.class.php

<?phpnamespace Model;use Think\Model;class GoodsModel extends Model{}

controller中实例化模型的方法:

第一种:

定义一个controller(GoodsController)来调用这个Goods模型类

<?phpnamespace Admin\Controller;use Model\GoodsModel;use Think\Controller;class GoodsController extends Controller{    public function test1(){        $goods = new GoodsModel();        echo '<pre>';        var_dump($goods);    }}

第二种:

使用M函数进行实例化:

<?phpnamespace Admin\Controller;use Model\GoodsModel;use Think\Controller;class GoodsController extends Controller{    public function test1(){        $goods = M('goods');        echo '<pre>';        var_dump($goods);    }}

第三种:

使用D函数

<?phpnamespace Admin\Controller;use Model\GoodsModel;use Think\Controller;class GoodsController extends Controller{    public function test1(){        $goods = D('goods');        echo '<pre>';        var_dump($goods);    }}

M方法和D方法是一样的

M()类似于 new Model()

D()类似于 new GoodsModel()

 

提示:可以看到goods表的信息,在模型中没有写代码,所有的业务逻辑都是Model类实现的


对表操作

增加:M(‘表名’)->add($date);

删除:M(‘表名’)->delete($id);

更新:M(‘表名’)->save($date);

查询:M(‘表名’)->select();

 

普通查询(显示所有的商品)

GoodsController中的代码:

<?phpnamespace Admin\Controller;use Model\GoodsModel;use Think\Controller;class GoodsController extends Controller{    public function showlist(){        $list = M('goods')->select();        $this->assign('list', $list);        $this->display();    }}

从模板中取出

<volist name="list" id="vo" ><tr id="product1">    <td>{$i}</td>    <td><a href="#">{$vo.goods_name}</a></td>    <td>{$vo.goods_number}</td>    <td>{$vo.goods_price}</td>    <td><img src="../../../Application/Admin/Public/img/20121018-174034-58977.jpg" height="60" width="60"></td>    <td><img src="../../../Application/Admin/Public/img/20121018-174034-97960.jpg" height="40" width="40"></td>    <td>{$vo.goods_brand_id}</td>    <td>{$vo.goods_create_time}</td>    <td><a href="#">修改</a></td>    <td><a href="javascript:;" onclick="delete_product(1)">删除</a></td></tr></volist>
原创粉丝点击