首页 > 解决方案 > 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>

标签: phplaravellaravel-5.6

解决方案


您收到“未定义的偏移量: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 文件中查询数据库!


推荐阅读