如何修复尝试访问数组偏移量类型为null的错误

bqujaahr  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(677)

我正在使用php创建一个时间表视图,在这个视图中,我根据日期和时间获取讲座数据。
这是我做的代码

  1. $monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
  2. $result_11to1 = mysqli_query($con, $monday_lectures);
  3. $m11to1 = mysqli_fetch_array($result_11to1);
  4. if ($m11to1["lecture_day"] == !'') {
  5. echo "<td>".$m11to1["lecture_name"]."</td>";
  6. } else {
  7. echo "<td> no class</td>";
  8. }

但我发现上面的代码有以下错误:
警告:试图访问c:\xampp\htdocs\nexgschool\admin\notify\add\u time\u table.php第45行中null类型值的数组偏移量

erhoui1w

erhoui1w1#

当您从数据库获取数据后收到此错误时,则表示数据库未找到任何匹配的行。大多数数据库获取函数返回 null 或者在没有匹配的记录或结果集已用尽时使用空数组。
要解决此问题,您需要检查值的真实性或要访问的键的存在性。

  1. $monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
  2. $result_11to1 = mysqli_query($con, $monday_lectures);
  3. $m11to1 = mysqli_fetch_array($result_11to1);
  4. if ($m11to1 && $m11to1["lecture_day"] == !'') {
  5. echo "<td>".$m11to1["lecture_name"]."</td>";
  6. } else {
  7. echo "<td> no class</td>";
  8. }

如果您想要的是结果数组中的一个值,那么您可以指定一个默认值,以防结果不存在。

  1. $monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
  2. $result_11to1 = mysqli_query($con, $monday_lectures);
  3. $m11to1 = mysqli_fetch_array($result_11to1);
  4. $lecture = $m11to1["lecture_day"] ?? null;

这同样适用于pdo。

  1. $monday_lectures = $pdo->prepare("SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'");
  2. $monday_lectures->execute();
  3. $m11to1 = $monday_lectures->fetch();
  4. $lecture = $m11to1["lecture_day"] ?? null;
展开查看全部

相关问题