Blogger Information
Blog 53
fans 3
comment 0
visits 46727
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
laravel原生数据库增删改查写法
emagic
Original
1172 people have browsed it

0916作业

laravel原生数据库增删改查写法

一、 .env文件中设置好数据库连接配置信息,改为对应的数据

二、控制器xxx.Controller中引入DB类

use Illuminate\Support\Facades\DB;

三、路由(web.php)中设置好对应的路径和方法,以便调试显示

浏览器地址栏中输入对应的路径运行

四、控制器xxx.Controller测试增删改查操作

  1. //查询
  2. public function sqlselect()
  3. {
  4. //:n 你也可以用其他字母,但是必须有:冒号 ,返回的是结果集
  5. $res = DB::select('SELECT `username`,`group_id`,`real_name`,`mobile` FROM `xpcms_admin` WHERE `id` >:n', ['n'=>2]);
  6. return $res;
  7. }
  8. // 插入
  9. public function sqlinsert()
  10. {
  11. $res = DB::insert('INSERT INTO `xpcms_admin` (`username`,`group_id`,`real_name`,`mobile`) VALUES ("gamemaster", "1","超级管理员","1390000000"),("vistor", "3","访客","13711111111")');
  12. return $res;
  13. }
  14. // 修改、更新
  15. public function sqlupdate()
  16. {
  17. $res = DB::update('UPDATE `xpcms_admin` SET `username` = ? WHERE `id` = ?', ['emagictest',24]);
  18. // 返回影响的行数
  19. return $res;
  20. }
  21. //删除
  22. public function sqldelete()
  23. {
  24. $res = DB::delete('DELETE FROM `xpcms_admin` WHERE `id`= ?' ,[24]);
  25. return $res;
  26. }

五、原生写法虽然可以操作,但是laravel也提供了更为方便的链式调用方法

  1. // 链式
  2. public function sqllianshi()
  3. {
  4. $res = DB::table('xpcms_admin')->where('id','>',15)->get();
  5. //table('表名')
  6. echo "<pre>";
  7. print_r($res);
  8. // where('字段名',[判断符:默认是等于],参数) 默认等于时只需要2个参数,默认中间是=;除此之外需要三个参数 ,中间参数为判断符号,如不等于<>,大于>,小于<
  9. }
  10. }
  • table('表名')

  • where('字段名',[判断符:默认是等于],参数) 默认等于时只需要2个参数,默认中间是=;除此之外需要三个参数 ,中间参数为判断符号,如不等于<>,大于>,小于<

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:我还是喜欢原生语法, 你呢?
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post