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编码。
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2026年06月01日 15时10分10秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
phpmailer发送邮件,可以带附件
2023-02-28
phpmyadmin 安装
2023-02-28
phpmyadmin数据库建表及插入
2023-02-28
phprpc简单使用
2023-02-28
phpstorm 2016.3.3 激活
2023-02-28
phpstorm中Xdebug的使用
2023-02-28
phpstorm中使用svn版本控制器
2023-02-28
phpstorm配置php脚本执行
2023-02-28
PhpStorm配置远程xdebug
2023-02-28
phpStudy安装教程
2023-02-28
phpunit
2023-02-28
phpweb成品网站最新版(注入、上传、写shell)
2023-02-28
phpWhois 项目推荐
2023-02-28
phpwind部署问题
2023-02-28
PHP_CodeIgniter Github实现个人空间
2023-02-28
php_crond:一个基于多进程的定时任务系统-支持秒粒度的任务配置
2023-02-28
PHP__call __callStatic
2023-02-28
PHP——修改数据库1
2023-02-28
PHP——封装Curl请求方法支持POST | DELETE | GET | PUT 等
2023-02-28