CI - show database error or fail

2019-01-29 04:14发布

问题:

I've developed a simple login system which works ok but fails, and I need to know why

QUESTION: How to show what is causing the fail. This is not a validation error but an error either with the data being passed to MySQL or the query somehow failing

here's the db function:

function login($email,$password)
{
    $this->db->where("email",$email);
    $this->db->where("password",$password);

    $query=$this->db->get("users");
    if($query->num_rows()>0)
    {
        foreach($query->result() as $rows)
        {
            //add all data to session
            $newdata = array(
                'user_id'  => $rows->id,
                'user_name'  => $rows->username,
                'user_email'    => $rows->email,
                'logged_in'  => TRUE,
            );
        }
        $this->session->set_userdata($newdata);
        return true;
    }
    return false;
}

And here's the logic:

public function login()
{
    $this->load->library('form_validation');
    // field name, error message, validation rules
    $this->form_validation->set_rules('email', 'Your Email', 'trim|required|valid_email');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');

    if($this->form_validation->run() == FALSE)
    {
        $this->signin();
    }
    else
    {
        $email=$this->input->post('email');
        $password=md5($this->input->post('pass'));
        $result=$this->user_model->login($email,$password);
        if($result)
        {
            $this->dash();
        }
        else
        {
            $data['title']= 'Login Error';
            $this->load->view('nav/header', $data);
            $this->load->view('login', $data);
            $this->load->view('nav/footer', $data);
        }
    }
}

I know the error is happening as I redirect back to login page if fail and change title text to show me (only in testing mode for right now) - but how can I find out what is going wrong with the query?

回答1:

You can use log_message and check the logs if the y behave as expected:

http://ellislab.com/codeigniter/user-guide/general/errors.html

I usually just use echo '<pre>'; print_r($query->result());die; just after the $query is formed. It's faster.



回答2:

$this->db->where("email",$email);
$this->db->where("password",$password);
$query=$this->db->get("users");
echo $this->db->last_query();
die();

you can echo the query you just did by using $this->db->last_query() this will show the query that your made with the values, and check if the query is valid.

read more at http://ellislab.com/codeigniter/user-guide/database/helpers.html