我正在尝试将数据合并到我已经创建的表中。这是显示它的代码。两个表名分别是students、teachers。在此代码中我收到一条错误消息
未定义的偏移量:0(视图:C:\xampp\htdocs\schoolmanagement\resources\views\displaycombineddata.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 文件中的数据库!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)