php - Laravel v5.6 错误显示此 "Undefined offset: 0 (View: C:\xampp\htdocs\schoolmanagement\resources\views\displaycombinedata.blade.php)"

标签 php laravel laravel-5.6

我正在尝试将数据合并到我已经创建的表格中。这是将显示它的代码。两个表名分别是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/

相关文章:

php - 单击清除或隐藏具有相同类名的标签

Laravel 9 给出错误的验证错误消息

php - 使用 laravel mysql 将列的数据转换为多列(将列的数据转换为特定列)

php - 我在哪里可以看到 Google App Engine 中的日志?

javascript - 在 Laravel 5.6 中使用自定义 JavaScript 函数

php - 如何删除 20 16 child 主题 Wordpress 下不可阻挡的链接下划线

php - Telegram Bot - 无法使用 PHP 删除自定义键盘

php - 如何在 Laravel 5.4 中使用 has-many-through 关系查询 3 个表

php - 在 nginx 上安装 PHP7.2 时出现 502 Bad Gateway

php - 搜索引擎不适用于我的分页器