我正在尝试将数据合并到我已经创建的表格中。这是将显示它的代码。两个表名分别是students、teachers。在此代码中,我收到一条错误消息
Undefined offset: 0 (View: 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>
最佳答案
你收到“Undefined offset: 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 文件中直接查询数据库!
关于php - Laravel v5.6 错误显示此 "Undefined offset: 0 (View: C:\xampp\htdocs\schoolmanagement\resources\views\displaycombinedata.blade.php)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50612342/