用thinkphp连接mysql数据库

一、设置mysql数据库的参数

thinkphpApplicationHomeConfconfig.php

<?php
return array(
    //'配置项'=>'配置值'
        'DB_TYPE'               =>  'mysql',     // 数据库类型
        'DB_HOST'               =>  'localhost', // 服务器地址
        'DB_NAME'               =>  'mydb',          // 数据库名
        'DB_USER'               =>  'root',      // 用户名
        'DB_PWD'                =>  '123',          // 密码
        'DB_PORT'               =>  '3306',        // 端口
        'DB_PREFIX'             =>  '',    // 数据库表前缀
        'DB_PARAMS'              =>  array(), // 数据库连接参数
        'DB_DEBUG'              =>  TRUE, // 数据库调试模式 开启后可以记录SQL日志
        'DB_FIELDS_CACHE'       =>  true,        // 启用字段缓存
        'DB_CHARSET'            =>  'utf8',      // 数据库编码默认采用utf8
        'DB_DEPLOY_TYPE'        =>  0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
        'DB_RW_SEPARATE'        =>  false,       // 数据库读写是否分离 主从式有效
        'DB_MASTER_NUM'         =>  1, // 读写分离后 主服务器数量
        'DB_SLAVE_NO'           =>  '' // 指定从服务器序号
);

二、编写连接数据库的代码

本示例是查询city表的第一行记录的cityname字段,然后将cityname字段的内容显示在页面上

thinkphpApplicationHomeControllerDemo1Controller.class.php

<?php
namespace HomeController;
use ThinkController;

class Demo1Controller extends Controller {
    public function index(){
            $city = M("city")->select();
            $this->assign('cityname',$city[0]['cityname']);
            $this->display();
        }
}

thinkphpApplicationHomeViewDemo1index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Hello,{$name}!
</body>
</html>

三、查询一个表,并且显示表中的数据

thinkphpApplicationHomeControllerDemo1Controller.class.php

<?php
namespace HomeController;
use ThinkController;

class Demo1Controller extends Controller {
    public function index(){
        $user = M("city")->select(); 
        $this->assign('list',$user);       
        $this->display();
    }
}

thinkphpApplicationHomeViewDemo1index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo1</title>
</head>
<body>
<table width="100%" border="1" cellspacing="0" cellpadding="0">
  <tr>
      <td>序号</td>
    <td>城市</td>
    <td>省会</td>
    <td>描述</td>
  </tr>
  <foreach name="list" item="item" key="index">
  <tr>
      <td>{$index+1}</td>
    <td>{$item.cityname}</td>
    <td>{$item.province}</td>
    <td>{$item.citydesc}</td>
  </tr>
  </foreach>
</table>
</body>
</html>

foreach是thinkphp内置的标签

四、将从数据库中查询中的数据以json的格式返回

<?php
namespace HomeController;
use ThinkController;

class Demo1Controller extends Controller {
    
    public function data(){
        $subject = M("tbsubject")->field('id,subjectname')->select();
    
        $this->ajaxReturn($subject,'JSON');
    }
}
原文地址:https://www.cnblogs.com/modou/p/5964819.html