1. Configuration file directory tp5\application\database.php
Connect through the configuration file. It can also be linked via methods.
The method in the controller is used to connect to the database; the query writing method is slightly different from the system DB class method.
// 使用方法配置数据库连接 public function data1 () { $DB = Db::connect([ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'user', // 用户名 'username' => 'root', // 密码 'password' => 'root', // 端口 'hostport' => '3306', ]); // dump($DB); // 查询数据,,,,和使用系统的DB类方法略有差异 $data = $DB -> table("uu") -> select(); dump($data); }
(recommended learning tutorial:thinkphp tutorial)
2. Basic usage, addition, deletion, modification and query
The controller uses the configuration file to connect to the database
The file under the controller (tp5\application\index\controller\Index.php )Write
fetch(); } // 使用配置文件连接数据库 public function data() { // 实例化数据库系统类 $DB = new Db; // 查询数据,表名为uu的所有数据 $data = $DB::table("uu") -> select(); // 使用sql语句 //$data = $DB::query("select * from uu"); dump($data); } }
3. Render the data to the template page
data(); return $this -> fetch(); } // 使用系统配置文件连接数据库 public function data() { // 实例化数据库系统类 $DB = new Db; // 查询数据 $data = $DB::table("uu") -> select(); $this -> assign("user",$data); // dump($data); } }
4. The template page can reference the rendering data
tp5\application\index\view\index\index .html
s s{volist name="user" id="vo"} {$vo.name} {/volist}
For more programming-related content, please pay attention to theIntroduction to Programmingcolumn on the php Chinese website!
The above is the detailed content of How to connect thinkphp5 to the database. For more information, please follow other related articles on the PHP Chinese website!