#ThinkPHP6.0-数据库操作-查询

连接数据库

解压后修改**.env**文件内的代码:

APP_DEBUG = true

[APP]
DEFAULT_TIMEZONE = Asia/Shanghai

[DATABASE]
TYPE = mysql
HOSTNAME = 数据库ip地址
DATABASE = 数据库名字
USERNAME = 数据库账号
PASSWORD = 数据库密码
HOSTPORT = 3306
CHARSET = utf8
DEBUG = true
[LANG]
default_lang = zh-cn

表数据查询

PHP代码

新建一个名称为:DataTest.php的文件;

<?php
namespace app\controller;
use think\facade\Db;
class DataTest
{
	public function index(){
        //查询数据库about表中的全部数据,根据mysql数据库设置的默认数量,返回相应数量的数据;
		$index_data=Db::table('about')->select();
		return json($index_data);
	}
}
?>

请求URL

https://localhost/index.php/DataTest/

返回数据

[{
    "id": 6,
    "title": "公告333",
    "content": "2022年11月16日 16:39:31公告内容"
}, {
    "id": 7,
    "title": "公告33333",
    "content": "2022年11月16日 16:39:31公告内容"
}, {
    "id": 8,
    "title": "公告33333",
    "content": "2022年11月16日 16:39:31公告内容"
}]

根据id查询

例如我们需要实现,根据查询about表中某个id的数据,则使用的方式为精准查询,id的值存在的,则返回相应的数据,否则返回[];

PHP代码

<?php

namespace app\controller;
use think\facade\Db;
class DataTest
{
	public function index(){
		$index_data=Db::table('about')->select();
		return json($index_data);
	}
	public function query_id($id){
		//根据id查询数据
		$id_data=Db::name('about')->where('id', '=', $id)->select();
		return json($id_data);
	}
}
?>

请求URL

例如我们查询about表中id为8的数据,则需要请求以下URL;

https://localhost/index.php/DataTest/query_id/?id=8

返回数据

[{
    "id": 8,
    "title": "公告33333",
    "content": "2022年11月16日 16:39:31公告内容"
}]

模糊搜索

例如要实现,根据关键词,进行模糊搜索about表中符合条件的内容,进行返回;

PHP代码

<?php

namespace app\controller;
use think\facade\Db;
class DataTest
{
	public function index(){
		$index_data=Db::table('about')->select();
		return json($index_data);
	}
	public function query_id($id){
		//根据id查询数据
		$id_data=Db::name('about')->where('id', '=', $id)->select();
		return json($id_data);
	}
	public function query_title($title){
		//模糊查询-标题
		$title_data=Db::name('about')->where('title', 'like', '%'.$title.'%')->select();
		return json($title_data);
	}
}

?>

请求URL

搜索一下关键词包含:公告,符合条件的内容

https://localhost/index.php/DataTest/query_title/?title=%E5%85%AC%E5%91%8A

返回数据

[{
    "id": 6,
    "title": "公告333",
    "content": "2022年11月16日 16:39:31公告内容"
}, {
    "id": 7,
    "title": "公告33333",
    "content": "2022年11月16日 16:39:31公告内容"
}, {
    "id": 8,
    "title": "公告33333",
    "content": "2022年11月16日 16:39:31公告内容"
}, {
    "id": 10,
    "title": "公告33333",
    "content": "2022年11月16日 16:39:31公告内容"
}, {
    "id": 16,
    "title": "app公告",
    "content": "app公告内容"
}, {
    "id": 17,
    "title": "app公告",
    "content": "app公告内容1111"
}]

扩展备注

更多关于ThinkPHP6.0数据库查询操作资料;

查询单个数据

https://www.kancloud.cn/manual/thinkphp6_0/1037533

查询表达式

https://www.kancloud.cn/manual/thinkphp6_0/1037537
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐