如何解决在 Codeigniter 4 中尝试访问 null 类型值的数组偏移量

How to solve Trying to access array offset on value of type null in Codeigniter 4

我想在Codeigniter 4中对登录activity进行验证,登录功能正常运行,但是验证有问题。当我尝试输入不存在的用户名时,会出现错误 and.says "Trying to access array offset on value of type null"

这是我的完整代码:

public function index()
{
    $M_admin = new \App\Models\M_admin();
    $login = $this->request->getPost('login');


    if ($login) {
        $member_username = $this->request->getPost('member_username');
        $member_password = $this->request->getPost('member_password');

        if ($member_username ==  '' or $member_password == '') {
            $err = "Please insert username and password";
        }

        if(empty($err)) {
            $dataMember = $M_admin->where("unm",
            $member_username)->first();
            
            if ($dataMember['unm'] != $member_username
            ){
                $err="Username does not exist";
            }else 
            if ($dataMember['u_p'] != $member_password
            ){
                $err="Incorrect password";
            }
        }
        
        if(empty($err)){
            $dataSesi = [
                'member_id' => $dataMember['id'],
                'member_username' => $dataMember['unm'],
                'member_password' => $dataMember['u_p'],
                ];
                session()->set($dataSesi);
                return redirect()->to('dashboard');
        }

        if ($err) {
            session()->setFlashdata('member_username', $member_username);
            session()->setFlashdata('error', $err);
            return redirect()->to("login");
        }
    }

    return view('v_login');
}

错误原因在这里:

 if ($dataMember['unm'] != $member_username
            ){
                $err="Username does not exist";
            }

我的代码有问题吗? 有帮助的答案意义重大,谢谢...

由于您没有“firstOrFail”函数,您应该在代码周围添加一个 try catch

$dataMember = $M_admin->where("unm",
            $member_username)->first(); 

如果用户不存在,您可能不想执行完整的检查过程,您也可以添加一个简单的“if(!empty($dataMember))”,但会在您的控制器中添加太多逻辑可能不是最好的方法,至少你应该创建一个私有函数来执行完整的检查逻辑和return“真”或“错误=”your_error_message

希望我的回答能对您有所帮助。 :)

条件 if ($dataMember['unm'] != $member_username) 没有意义,因为您正在根据此值查询数据。

$dataMember = $M_admin->where("unm", $member_username)->first();

如果您从此方法得到结果,$dataMember['unm'] 必须等于 $member_username

您需要做的是检查变量 $dataMember 是否为空。

if (empty($dataMember)) {
  $err = "Username does not exist";
} elseif ($dataMember['u_p'] != $member_password) {
  $err = "Incorrect password";
}

[已解决] 我在验证前做空值检查,所以代码看起来像这样

if (empty($err)) {
            $dataMember = $M_admin->where("unm", $member_username)->first();
            if (empty($dataMember)) {
                $err = "Invalid Username!";
            } else
            if ($dataMember['u_p'] != SHA1($member_password)) {
                $err = "Incorrect Password1";
            }
        }