Home > Mobile >  How to create login API in Codeigniter PHP
How to create login API in Codeigniter PHP

Time:09-17

Controller:-

public function login($email,$password)
    {
        $table="test_api";
        
        $email='[email protected]';
        $password='123456';

        
        
$result = $this->Webservice_model->login($email,$password);
$data[]=$result;
    if($result){
        $json = array("result"=>$data, "status"=>1, "msg"=>"Login Successfully!");
    }else{
        $json = array("result"=>$data, "status"=>0, "msg"=>"Login Failed!");
    }

    header('Content-type: application/json');
    echo json_encode($json);

}

Model:-

public function login($email, $password)
            {
                $this->db->where('email',$email);
                $this->db->where('password',$password);     
                $query = $this->db->get('test_api');

                if($query->num_rows() == 1)
                {
                    return $query->row();
                }
                else
                {
                    return false;
                }
            }

when I Use this path it does not give me result.

Webservice/[email protected]&password=123456

CodePudding user response:

You can get the query strings by using CI_input:

public function login()
    {
        $email = $this->input->get('email');
        $password = $this->input->get('password');

        $result = $this->Webservice_model->login($email, $password);
        $data[] = $result;
        if ($result) {
            $json = array("result" => $data, "status" => 1, "msg" => "Login Successfully!");
        } else {
            $json = array("result" => $data, "status" => 0, "msg" => "Login Failed!");
        }

        header('Content-type: application/json');
        echo json_encode($json);
    }

CodePudding user response:

As you are using Codeigniter 3, you might take a look at this method. With this, you can call the query inside the Controller and also had the API header settings. This will not be practiced in Codeigniter 4 btw.

public function login() {
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

    $email= $this->input->post('email');
    $password = $this->input->post('password');

    $this->db->select('email,password');
    $this->db->from('test_api');

    $this->db->where('email', $email);
    $this->db->where('password', md5($password));
    $query = $this->db->get();
    $result = $query->row();

    if ($result != null) {
        echo json_encode($result);
    } else {
        echo json_encode('false');
    }
}
  • Related