Blogger Information
Blog 39
fans 0
comment 0
visits 30544
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
lavarel基础1:数据库查询、新增、删除、修改(一)
Original
913 people have browsed it

一、环境准备

1.在lavarel目录下创建控制器:homecontr.php

命令行:php artisan make:controller homecontr.php

2.创建一个表:articles,录入5条以上数据。

二、数据库查询

1.配置数据库连接

目录:.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=exe05
DB_USERNAME=exe
DB_PASSWORD=exE123

2.采用内置的静态方法DB:select()

(1)创建新控制器homecontr.php代码:

目录:laravel7\app\Http\Controllers

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Support\Facades\DB;
  4. class homecontr extends Controller
  5. {
  6. public function get(){
  7. $res = DB::select('select * from articles');
  8. // 把结果转化为二维数组
  9. $data = [];
  10. foreach ($res as $val) {
  11. $data[] = (array)$val;
  12. }
  13. // 把数组的key值存入变量$key['result']
  14. $key ['result'] = $data;
  15. // echo '<pre>';
  16. // print_r($data);
  17. // print_r($key);
  18. // 把二维数组的结果渲染视窗
  19. return view('table',$key);
  20. }
  21. }

(2)创建新视窗引擎table.blade.php

目录:laravel7\resources\views
引入layui美化输出表格:拷贝\layui目录到laravel7\public\layui

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <link rel="stylesheet" type="text/css" href="/layui/css/layui.css" />
  5. <title>table</title>
  6. </head>
  7. <body>
  8. <table class="layui-table">
  9. <caption>文章列表</caption>
  10. <thead>
  11. <tr>
  12. <th>id</th>
  13. <th>title</th>
  14. </tr>
  15. </thead>
  16. <tbody>
  17. <!-- 循环遍历数组 -->
  18. <?php foreach($result as $val){?>
  19. <tr>
  20. <td><?php echo $val['id']?></td>
  21. <td><?php echo $val['title']?></td>
  22. </tr>
  23. <?php } ?>
  24. </tbody>
  25. </table>
  26. </body>
  27. </html>

(3)添加路由

目录:laravel7\routes\web.php

  1. <?php
  2. use Illuminate\Support\Facades\Route;
  3. Route::get('db/select','homecontr@get');

实例输出效果:

总结:
数据库查询步骤:配置数据库连接(.env)->创建控制器调用静态方法(DB:select())->利用视窗渲染输出(blade)。
由于基础不好,对以下语句不是很明白:

  1. $key ['result'] = $data;
  2. // 把二维数组的结果渲染视窗
  3. return view('table',$key);
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