Home> PHP Framework> ThinkPHP> body text

How to connect thinkphp5 to the database

王林
Release: 2020-03-05 10:52:44
forward
4624 people have browsed it

How to connect thinkphp5 to the database

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); }
Copy after login

(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); } }
Copy after login

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); } }
Copy after login

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}
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!