用thinkphp鏈接mysql數據庫

1、設置mysql數據庫的參數php

thinkphp\Application\Home\Conf\config.phphtml

<?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'           =>  '' // 指定從服務器序號
);

 

2、編寫鏈接數據庫的代碼mysql

本示例是查詢city表的第一行記錄的cityname字段,而後將cityname字段的內容顯示在頁面上ajax

thinkphp\Application\Home\Controller\Demo1Controller.class.phpsql

<?php
namespace Home\Controller;
use Think\Controller;

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

 

thinkphp\Application\Home\View\Demo1\index.htmlthinkphp

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

 

3、查詢一個表,而且顯示錶中的數據數據庫

thinkphp\Application\Home\Controller\Demo1Controller.class.phpjson

<?php
namespace Home\Controller;
use Think\Controller;

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

 

thinkphp\Application\Home\View\Demo1\index.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內置的標籤服務器

 

4、將從數據庫中查詢中的數據以json的格式返回

<?php
namespace Home\Controller;
use Think\Controller;

class Demo1Controller extends Controller {
    
    public function data(){
        $subject = M("tbsubject")->field('id,subjectname')->select();
    
        $this->ajaxReturn($subject,'JSON');
    }
}
相關文章
相關標籤/搜索