php - Laravel v5.6 错误显示此“未定义偏移量:0(查看:C:\xampp\htdocs\schoolmanagement\resources\views\displaycombinedata.blade.php)”
问题描述
我正在尝试将数据组合到我已经创建的表中。这是将显示它的代码。两个表名是students,teachers。在这段代码中,我收到一条错误消息
未定义偏移量:0(查看:C:\xampp\htdocs\schoolmanagement\resources\views\displaycombinedata.blade.php)
请帮帮我。
<head>
<title>
Display Combined Data
</title>
<h1>Display Combine Data from Database</h1>
</head>
<body>
<table>
<thead>
<th>S.No.</th>
<th>Student Name</th>
<th>Student Class</th>
<th>Student Age</th>
<th>class Teacher</th>
<th>Teacher salary</th>
</thead>
<tbody>
<?php for($i=1; $i<=DB::table('students')->count(); $i++):?>
<tr>
<?php $result=DB::table('students')->where('students_id','=',$i)->get();
?>
<td>{{($result[0]->students_id)}}</td>
<td>{{($result[0]->students_name)}}</td>
<td>{{($result[0]->students_class)}}</td>
<td>{{($result[0]->students_age)}}</td>
<td>{{($result[0]->class_teacher)}}</td>
<?php $result1= DB::table('teachers')->where('teachers_name','=',$result[0]->class_teacher)->get();
if($result1 == null) {?>
<td>NA</td>
<?php } else{?>
<td>{{($result1[0]->salary)}}}</td>
<?php } ?>
</tr>
<?php: @endfor ?>
</tbody>
</table>
</body>
解决方案
您收到“未定义的偏移量:0”错误,因为
$result=DB::table('students')->where('students_id','=',$i)->get();
是空的。在这段代码中,
<td>{{($result[0]->students_id)}}</td>
您正在尝试从空数组的第一条记录中获取数据。
相反,您应该首先检查结果是否为空,并且仅当它不为空时才尝试获取该属性。
@if (!empty($result))
<td>{{($result[0]->students_id)}}</td>
<td>{{($result[0]->students_name)}}</td>
<td>{{($result[0]->students_class)}}</td>
<td>{{($result[0]->students_age)}}</td>
<td>{{($result[0]->class_teacher)}}</td>
@endIf
请注意,您真的不应该直接在 Blade 文件中查询数据库!
推荐阅读
- r - 如何为绘图中的一行设置 scale_x_date
- esp8266 - ESP 32 和 8266 的共享代码库?
- asp.net-core - 当断言函数返回预期的 DTO 对象时,如何在 DTO 对象类的 getter 上获得 100% 的测试覆盖率?
- node.js - 让节点 REPL 在文件更改时重新加载导入的模块?
- mysql - 如何在数据库左窗格中恢复 PHPMyAdmin 函数视图
- c# - 无法使用 C# auth 从某些套接字中找到只读域控制器
- linux - 关于用于构建和运行的 Boot2docker 设置的一些问题
- firebase-realtime-database - 错误:身份验证选项与现有会话令牌不匹配,也不是交互式会话,因此无法手动重新身份验证
- java - 监听集合中的多个文档并更新recyclerview
- c# - 如何获取与列表视图数据模板中存在的复选框关联的值?