Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:意思是:数组的某个元素,也可以是一个数组类型,即二维数组
命令行:php artisan make:controller homecontr.php
目录:.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=exe05
DB_USERNAME=exe
DB_PASSWORD=exE123
目录:laravel7\app\Http\Controllers
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class homecontr extends Controller
{
public function get(){
$res = DB::select('select * from articles');
// 把结果转化为二维数组
$data = [];
foreach ($res as $val) {
$data[] = (array)$val;
}
// 把数组的key值存入变量$key['result']
$key ['result'] = $data;
// echo '<pre>';
// print_r($data);
// print_r($key);
// 把二维数组的结果渲染视窗
return view('table',$key);
}
}
目录:laravel7\resources\views
引入layui美化输出表格:拷贝\layui目录到laravel7\public\layui
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/layui/css/layui.css" />
<title>table</title>
</head>
<body>
<table class="layui-table">
<caption>文章列表</caption>
<thead>
<tr>
<th>id</th>
<th>title</th>
</tr>
</thead>
<tbody>
<!-- 循环遍历数组 -->
<?php foreach($result as $val){?>
<tr>
<td><?php echo $val['id']?></td>
<td><?php echo $val['title']?></td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
目录:laravel7\routes\web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('db/select','homecontr@get');
实例输出效果:
总结:
数据库查询步骤:配置数据库连接(.env)->创建控制器调用静态方法(DB:select())->利用视窗渲染输出(blade)。
由于基础不好,对以下语句不是很明白:
$key ['result'] = $data;
// 把二维数组的结果渲染视窗
return view('table',$key);