一、設置mysql數據庫的參數
thinkphp\Application\Home\Conf\config.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字段的內容顯示在頁面上
thinkphp\Application\Home\Controller\Demo1Controller.class.php
<?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.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> Hello,{$name}! </body> </html>
三、查詢一個表,並且顯示表中的數據
thinkphp\Application\Home\Controller\Demo1Controller.class.php
<?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內置的標簽
四、將從數據庫中查詢中的數據以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'); } }