First, set the parameters of MySQL database
thinkphp\application\home\conf\config.php
<?PHPreturn Array( //' Config item ' = ' config value '' Db_type ' = ' mysql ',//Database Type' db_host ' = ' localhost ',//Server Address' Db_name ' = ' mydb ',//Database name' Db_user ' = ' root ',//User name' db_pwd ' = ' 123 ',//Password' Db_port ' = ' 3306 ',//Port' Db_prefix ' = ',//database table Prefixes' Db_params ' =Array(),//Database Connection Parameters' Db_debug ' =TRUE,//SQL log can be logged when database debug mode is turned on' Db_fields_cache ' =true,//Enable field caching' Db_charset ' = ' UTF8 ',//database encoding is UTF8 by default' Db_deploy_type ' = 0,//Database Deployment method: 0 Centralized (single server), 1 distributed (Master-slave server)' Db_rw_separate ' =false,//whether the database reads and writes separate master-slave valid' Db_master_num ' = 1,//number of master servers for read-write separation' Db_slave_no ' and ' = '//Specify the number from the server);
Second, write the code to connect the database
This example is the CityName field that queries the first row of records in the city table and then displays the contents of the CityName field on the page
thinkphp\application\home\controller\demo1controller.class.php
<? phpnamespace Home\controller; Use Think\controller; class extends Controller { publicfunction index () { $user = M ("City")- >Select (); $this->assign (' CityName ',$user[0][' CityName ']); $this, display ();} }
Thinkphp\application\home\view\demo1\index.html
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "UTF-8"><title>Insert Title here</title></Head><Body>hello,{$name}!</Body></HTML>
Iii. querying a table and displaying the data in the table
thinkphp\application\home\controller\demo1controller.class.php
<? phpnamespace Home\controller; Use Think\controller; class extends Controller { publicfunction index () { $user = M ("City")- >Select (); $this->assign (' list ',$user); $this, display ();} }
Thinkphp\application\home\view\demo1\index.html
<! DOCTYPE html>foreachkey= "index" > <tr> <td>{$index+1} </td> <td>{$item.cityname}</td> <td>{$item. Province} </td> <td>{$item.citydesc}</td> </tr> </foreach ></table></body>
foreach is a thinkphp built-in label
Connect MySQL database with thinkphp