从ThinkPHP3.2.3过渡到ThinkPHP5.0学习笔记图文详解(6)
//添加多条数据
$data = [
['article_title' => '标题1', 'article_content' => '内容1'],
['article_title' => '标题2', 'article_content' => '内容2'],
['article_title' => '标题3', 'article_content' => '内容3']
];
db('article')->insertAll($data);
修改数据:tp3.2使用save(),tp5使用 update()
//修改数据
$whe['article_id'] = 1;
$data['article_title'] = '修改后的标题';
db('article')->where($whe)->update($data);
删除数据:没错还是 delete()
//删除数据
$whe['article_id'] = 1;
db('article')->where($whe)->delete();
db()助手使用起来比较方便,但每次都会重新连接数据库,因此应当尽量避免多次调用,建议还是使用Db类操作数据库。
Db类操作原生SQL:
<?php
namespace app\index\controller;
use think\Db;
class Index {
public function index() {
// 插入记录
$res = Db::execute('insert into lws_article (title ,content) values ("标题", "内容")');
// 删除数据
$res = Db::execute('delete from lws_article where art_id = 1 ');
// 更新记录
$res = Db::execute('update lws_article set title = "修改标题" where art_id = 1 ');
// 查询数据
$res = Db::query('select * from lws_article where art_id = 1');
// 显示数据库列表
$res = Db::query('show tables from blog');
// 清空数据表
$res = Db::execute('TRUNCATE table lws_article');
}
}
Db类操作查询构造器:
<?php
namespace app\index\controller;
use think\Db;
class Index {
public function index() {
// 查询数据(数据库没有配置表前缀)
$res = Db::table('lws_article')
->where('art_id', 1)
->select();
//以下为数据库配置了表前缀
// 插入记录
$res = Db::name('article')
->insert(['title' => '标题', 'content' => '内容']);
// 更新记录
$res = Db::name('article')
->where('art_id', 1)
->update(['title' => "修改标题"]);
// 查询数据
$res = Db::name('article')
->where('art_id', 1)
->select();
// 删除数据
$res = Db::name('article')
->where('art_id', 1)
->delete();
//链式操作举例
$artlist = Db::name('article')
->where('is_del', 'N')
->field('id,title,content')
->order('post_time', 'desc')
->limit(10)
->select();
}
}
【切换数据库】
首先在数据库配置中配置多个数据库:
// 数据库配置1
'db1' => [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'blog1',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => '123456',
// 数据库连接端口
'hostport' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => 'lws_',
],
// 数据库配置2
'db2' => [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'blog2',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => '',
// 数据库连接端口
'hostport' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => 'lws_',
],
内容版权声明:除非注明,否则皆为本站原创文章。
