用thinkphp连接mysql数据库
1.需要先在application文件夹内的database.php文件里添加上自己mysql的用户名、密码、库名、数据库链接参数。
// 数据库连接参数
28 'params' => [
29 // 使用长连接
30 \PDO::ATTR_PERSISTENT => true,
31 ],
2.回到自己的controller文件夹内,编辑Index.php文件。
(1)先导入两个类(没学过php感觉就跟oc里面的类的声明一样)。
<?php
2 namespace app\demo\controller;
3
4 use think\Controller;
5 use think\Db;
(2)继承controller(感觉跟oc里的继承是一回事)。
7 class Indexextends Controller
8 {
9 publicfunction index()
10 {
11
12 }
13 }
(3)现在只要获取数据库的数据就行了。
. 7 class Indexextends controller
8 {
9 publicfunction index()
10 {
11 $result= Db::query('select * from 表名');
12 return dump($result);
13 }
14 }
(4)好像还有另一种获取sql数据方式,试试先。
7 class Index extends controller
8 {
9 public function index()
10 {
11 /*$result = Db::query('select * from user');
12 return dump($result);*/
13 $data = Db::name('表名') -> select();
14 return dump($data);
15 }
16 }
(5)再添一个连接方法吧,用的是connect()链接数据库(我一直觉得php里一串英文跟着个括号的东西跟函数没什么两样)。
class Index extends controller
8 {
9 publicfunction index()
10 {
11 /*$result = Db::query('select * from user');
12 return dump($result);*/
13 /*$data = Db::name('user') -> select();
14 return dump($data);*/
15 $test= Db::connect('mysql://sql用户名:密码@127.0.0.1:3306/库名#utf8' )->query('select * from 表名');
14 return dump($test);
17 }
18 }
这样也能连上呢!!!3.修改mysql的数据好像不能用query('sql语言'),需要用execute('sql语言'),关于execute这个函数就不做示范了以后还会用到,额,在view文件夹里头有个index文件夹编辑里头的index.html文件就能美化输出的数据了,第一篇就写这些吧。