php原生代码怎么连表查询,PHP tp5中使用原生sql查询代码实例
发布日期:2025-05-04 04:13:18 浏览次数:9 分类:精选文章

本文共 2091 字,大约阅读时间需要 6 分钟。

ThinkPHP数据库操作指南

1. 数据库配置

database.php 文件中,需先完成数据库的基本配置。数据库操作必须严格使用 use think\Db; 命名空间进行调用。

数据库配置示例如下:

'db2' => [    'type' => 'mysql',    'hostname' => '127.0.0.1',    'database' => 'tpshop2',    'username' => 'root',    'password' => '',    'charset' => 'utf8',    'prefix' => 'tp_',],

2. 数据库操作方法

1. 插入记录

使用 Db::execute 方法执行插入操作:

$result = Db::execute('insert into sb_ad (ad_name, ad_content ,status) values (1, "456", 1)');// 查看结果dump($result);

2. 更新记录

使用 Db::execute 方法执行更新操作:

$result = Db::execute('update sb_ad set ad_name = "framework" where ad_id = 1');// 查看结果dump($result);

3. 查询数据

使用 Db::query 方法执行查询操作:

$result = Db::query('select * from sb_ad where ad_id = 1');// 查看结果print_r($result);

4. 删除数据

使用 Db::execute 方法执行删除操作:

$result = Db::execute('delete from sb_ad where ad_id = 2');// 查看结果dump($result);

5. 数据库管理

a. 显示数据库列表

$result = Db::query('show tables from tpshop1');// 查看结果print_r($result);

b. 清空数据表

$result = Db::execute('TRUNCATE table sb_ad');// 查看结果dump($result);

3. 多数据库操作

application/config.php 文件中添加多数据库配置,例如:

'db2' => [    'type' => 'mysql',    'hostname' => '127.0.0.1',    'database' => 'tpshop2',    'username' => 'root',    'password' => '',    'charset' => 'utf8',    'prefix' => 'tp_',],

4. 数据库连接与操作

1. 单次数据库连接

$result = Db::connect('db2')->query('select * from sb_ad where ad_id = 1');// 查看结果print_r($result);

2. 多次数据库连接

$db1 = Db::connect('db1');$db2 = Db::connect('db2');// 执行查询$resultDb1 = $db1->query('select * from sb_ad where ad_id = 1');$resultDb2 = $db2->query('select * from sb_ad where ad_id = 1');

5. 参数绑定

1. 参数传递

使用数组形式传递参数:

$result = Db::execute('insert into sb_ad (ad_name, ad_content ,status) values (?, ?, ?)', [3, 'thinkphp', 1]);// 查看结果dump($result);

2. 命名占位符

$result = Db::execute('insert into sb_ad (ad_name, ad_content ,status) values (:ad_name, :ad_content, :status)', [    'ad_name' => 11,    'ad_content' => 'thinkphp',    'status' => 1]);// 查看结果dump($result);

3. 查询参数绑定

$result = Db::query('select * from sb_ad where ad_id = ?', [3]);// 查看结果print_r($result);

6. 数据库优化

在实际使用中,建议根据数据库类型和连接方式进行适当的优化设置。例如,MySQL数据库默认字符集为utf8,建议统一使用utf8编码。

上一篇:PHP去掉转义符
下一篇:PHP区分 企业微信浏览器 | 普通微信浏览器 | 其他浏览器

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2026年06月01日 15时10分10秒