博客
关于我
php原生代码怎么连表查询,PHP tp5中使用原生sql查询代码实例
阅读量:793 次
发布时间:2023-03-01

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

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编码。

转载地址:http://vjtfk.baihongyu.com/

你可能感兴趣的文章
phpnow配置
查看>>
phprpc简单使用
查看>>
phpspider中当爬虫获取数据时如何去掉广告
查看>>
phpstorm 2016.3.3 激活
查看>>
phpstorm中Xdebug的使用
查看>>
phpstorm中使用svn版本控制器
查看>>
phpstorm配置php脚本执行
查看>>
PhpStorm配置远程xdebug
查看>>
phpstudy+iis搭建php项目
查看>>
phpStudy安装教程
查看>>
phpstudy搭建网站,通过快解析端口映射外网访问
查看>>
phpunit
查看>>
PHPUnit单元测试对桩件(stub)和仿件对象(Mock)的理解
查看>>
phpweb成品网站最新版(注入、上传、写shell)
查看>>
phpWhois 项目推荐
查看>>
Redis事务详解,吃透数据库没你想的那么难
查看>>
phpwind部署问题
查看>>
PHP_CodeIgniter Github实现个人空间
查看>>
php_crond:一个基于多进程的定时任务系统-支持秒粒度的任务配置
查看>>
PHP__call __callStatic
查看>>