I have recently starting following some coding tutorials for PHP CodeIgniter and I have run into a bit of a snag for my login and registration system. The registration works perfectly, accessing the database and creating accounts but there is a problem with my login code that I can not work my head around.
I receive the following error:
A PHP Error was encountered Severity: Notice
Message: Trying to get property 'email' of non-object
Filename: controllers/Auth.php
Line Number: 23
Backtrace:
File: /opt/lampp/htdocs/application/controllers/Auth.php Line: 23 Function: _error_handler
File: /opt/lampp/htdocs/index.php Line: 315 Function: require_once
The code for the following is:
<?php
class Auth extends CI_Controller{
public function login()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if($this->form_validation->run() == TRUE) {
$username = $_POST['username'];
$password = md5($_POST['password']);
//check user in db
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username'=>$username, 'password'=>$password));
$query = $this->db->get();
$user = $query->row();
if ($user->email){
$this->session->set_flashdata("success", "You are logged in.");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
//redirect to profile page
redirect("user/profile", "refresh");
} else {
$this->session->set_flashdata("error", "NO such account exists");
//redirect("auth/login", "refresh");
}
}
$this->load->view('login');
}
public function register()
{
if(isset($_POST['register'])) {
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
$this->form_validation->set_rules('password', 'Confirm Password', 'required|min_length[5]|matches[password]');
if($this->form_validation->run() == TRUE) {
//echo 'form validated';
//add user in database
$data = array(
'username'=>$_POST['username'],
'email'=>$_POST['email'],
'password'=> md5($_POST['password'])
);
$this->db->insert('users', $data);
$this->session->set_flashdata("success", "Your account has been registered");
redirect("auth/register", "refresh");
}
}
$this->load->view('register');
}
}
?>
Any help would be appreciated and if anymore code that I have used for this tutorial is needed for a solution, just let me know.
Thank you.