This question already has answers here:
"call to undefined function" error when calling class method
(4 answers)
Closed 9 years ago.
I'm new to MVC patterns and OOP in general.
I have an application in CodeIgniter, and the basic part works. There is a form that asks for a username and password. If they match the database, the user is logged in, a session is created and they are redirected to another part of the site. This all works fine.
I now want to add two more functions, one updateloggedonuser is to update the database when the user is logged in, set a bit field to 1 and set a timestamp.
The other is getusersname. This one I want to get the logged on user's firstname, lastname and ID from the database and return them so I can store them in a session variable.
I am getting a Fatal error: Call to undefined function getusersname().
Controller:
class Login_c extends CI_Controller {
function index (){
$view['main_content'] = 'loginform_view';
$this->load->view('includes/template', $view);
}
function validate_credentials() {
$this->load->model('login_m');
$query = $this->login_m->validate();
if($query) // if the users credentials valid
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site_c/main_area');
}
else
{
$this->index();
}
}
function logout(){
$this->index();
$this->session->sess_destroy();
}
}
Model:
class Login_m extends CI_Model {
function validate(){
$this->db->where('UserName', $this->input->post('username'));
$this->db->where('UserPassword', md5($this->input->post('password')));
$query = $this->db->get('User');
$userN = $this->input->post('username');
if($query->num_rows == 1)
{
getusersname($UserN);
updateloggedonuser($UserN);
return true;
}
}
function updateloggedonuser($UserN){
// with username set isActive to 1 and Updatedate to update 'datetime'
$date = new DateTime();
$data = array('isActive' =>1,
'UpdateDate' => $date);
$this->db->where('UserName', $UserN);
$this->db->update('User',$data);
}
function getusersname($UserN){
// with username get FirstName , LastName and UserID from Database
$sql = "SELECT UserID, FirstName, LastName FROM User WHERE UserName =?";
$q= $this->db->query($sql,$UserN);
if($q->num_rows() ==1){
foreach ($q->result() as $row) {
$userdata[] = $row;
}
return $userdata;
}
}
}
I think you can see what I'm trying to do, but obviously I'm not doing it the right way.
Try like this
$this->my_function_name();
So they would be
if($query->num_rows == 1)
{
$this->getusersname($UserN);
$this->updateloggedonuser($UserN);
return true;
}
$this actually represents the singleton Codeigniter instance which is actually the controller object.
In the second modal example, you need to change getusername() to $this->getusername();
function validate(){
$this->db->where('UserName', $this->input->post('username'));
$this->db->where('UserPassword', md5($this->input->post('password')));
$query = $this->db->get('User');
$userN = $this->input->post('username');
if($query->num_rows == 1)
{
$this->getusersname($UserN);
$this->updateloggedonuser($UserN);
return true;
}
}
You want to call the method, therefore you need to add $this-> to the method call:
$this->getusersname($UserN);
In quite a few programming languages a function call within a class method is interpreted as a method call. In PHP you have always to specify you want to call a method with $this-> otherwise he will look at the global function namespace.
Related
I am new to codeigniter and I am trying to make a login authentication system with the role of admin, moderator, and user.
My problem is that I am trying to set a condition on 'role' which is a column in database. But I don't know how to use and compare the value of column role.
I wrote the following code but I am getting error:
[Severity: Error Message: Call to a member function result_array() on array]
My code is:
<?php
// step no 4 create a new controller where form post after submission.
class verify extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load->model('user');
}
function login(){
//step no 5 create a new method in verify controller
$username = $this->input->post('username');
$userpass = $this->input->post('password');
//step 9 take value back in answer variable from model and print message
$answer = $this->user->usergetdata($username,$userpass,'admin');
$data = $answer->result_array();
if($answer){
if($data[0]['role']=='admin'){
redirect('admin_page');
}
}else
{
echo "username or Password is wrong";
}
}
}
?>
<!-- begin snippet: js hide: false console: true babel: false -->
In model
$res = $this->db->get();
return $res->result_array();
then apply
foreach($answer as $a)
{
var_dump( $a );
}
use $a to get values
$data = json_decode(json_encode($answer),true);
print_r($data);
used this your result convert in array format
You are calling the ->result() in you model and then trying to call the result array from the controller.
Either remove the ->result(); from the return $query->result(); in the model or remove the ->result_array() from the controller.
Once you have called the script and used ->get() you can only call one of the results at a time. If you are likely to want to call different result parameters such as ->result() and ->num_rows on the same query result then just return the query to the controller and use ->result() in the controller.
Hope this helps clear things up a little.
MODEL
class user extends CI_Model
{
function __construct()
{
parent::__construct();
}
function usergetdata( $username,$userpass,$role )
{
$this->db->select();
$this->db->from( 'user' );
$this->db->where( 'username',$username );
$this->db->where( 'userpass',$userpass );
$query= $this->db->get();
if( $query->num_rows() == 1 )
{
return $query;
}
else
{
return false;
}
}
}
CONTROLLER
$answer = $this->user->usergetdata( $username,$userpass,'admin' );
$data = $answer->result_array();
i am trying to learn codeigniter, and i start with basic login function. Everything works well, until i want to redirect member to their homepage.
i seems like codeigniter can not redirect to it. It just always stops at this url:
I want this redirect to the site/members_area like mycode. This is my controller code:
class login extends ci_controller{
function index(){
$data['main_content'] = 'login_form';
$this->load->view('includes/template.php', $data);
}
function validate_credentials(){
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query)//user's credentails validated
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true);
$this->session->set_userdata($data);
redirect('site/members_area');
}
else
{
$this->index();
}
}
}
And this is my model code:
class Membership_model extends ci_model{
function validate(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('membership');
if($query->num_rows == 1){
return true;
}
}
}
I already input helper url and form in my autoload, but it still does not work.
Can someone help?
num_rows is a function and should have parentheses like this: $query->num_rows()
You can eliminate the if and simply use
return $query->num_rows() > 0;
new to stack overflow (and codeigniter!) and I'm running into this issue on my first project, naturally... I'm sure its a bonehead error on my part, but I've been researching and trying to figure it out for the last few hours and I cat seem to figure it out...
I have the database library autoloaded, but everytime I try to use the methods in my model I get this error:
"Fatal error: Call to a member function where() on a non-object in application\models\user_model.php on line 13"
this is my User controller method called by the form action from my login form view:
function login() {
$this->load->model('user_model');
$query = $this->user_model->validate();
if ($query)
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('members');
}
else
{
$this->load->view('user');
}
} // end login function
this is my model:
<?php
class User_model extends CI_Model {
function __construct() {
parent::__construct();
}
// -------------------------------------------------------------------------------
// validate(): query db for user/pass and return true or false
function validate() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', sha1($this->input->post('password')));
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
return true;
}
} // end validate function
// -------------------------------------------------------------------------------
function check()
{
$dbo = $this->load->database('default',TRUE);
$query = $this->$dbo->get('users');
echo $query->num_rows();
}
} // end user_model class
when I was attempting to debug the issue, I added the db methods to the controller and they worked fine... when using them in my model they dont want to work for whatever reason and throw the fatal error I mentioned. Appreciate any help you guys can throw my way.
Thanks in advance!
(using codeigniter 2.1)
EDIT:
Just to clear things up a little bit more, When I add the validate method (from my model) to my controller, I get no errors, and everything works fine... But when leaving it in the model and calling it from the controller I get the fatal error
You missed $query = part, Should be:
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
return true;
}
Edited:
I think you have not added all the parent constructor, try:
class Users extends CI_Model {
function __Users() {
parent::__CI_Model();
$this->load->database();
}
I think the function validate in your model should be like this
// validate(): query db for user/pass and return true or false
function validate($username,$password) {
$this->db->where('username', $username);
$this->db->where('password', sha1($password));
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
return true;
}
} // end validate function
In your controller you can call it like so
function login()
{
$query =$this->user_model->validate($this->input->post('username'),$this->input->post('password'));
// the rest
}
Here is my controller
public function login() {
$this->load->model('admin_model');
$access = $this->admin_model->check_login();
$data['content'] = 'content/home';
$data['title'] = 'Admin Panel Login';
if($access) {
$data= array(
'email' => $this->input->post('email'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('admin/index/dashboard');
} else {
$this->index($page = 'home', $msg = 'failure');
}
Here is my model
public function check_login() {
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('customers');
return (bool) $query->num_rows;
}
So what I have been working on is a function in my Admin constructor that will ensure that users cannot access any page until they are logged in. The problem is that when I go to admin/login, it is setting is_logged_in to true, even though the check_login function should be returning as false. It's saying that it is finding a row, even though there is only 1 row in my DB right now which it shouldn't be matching.
I'm new to CI, so please be gentle. :)
num_rows() is a method (not a property) and should be used more like this:
return $query->num_rows() > 0;
An expansion on Colin's answer:
public function check_login() {
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('customers');
if ($query->num_rows()>0) {
return TRUE;
} else {
return FALSE;
}
}
I didn't see the point in your model.
A model can't (or even if it can, shouldn't) get the variables from the view. It should come via controller.
Are you sure, the post variables are appearing in the model?
Better solution. Catch the post variables in controller.
In the model, create functions with parameters.
Then in the controller, retrieve it like this.
$data['bla'] = $this->admin_model->method_name($this->input->post('blabla'));
this will prevent all these confusions.
From a user login form i need to use their username ($this->input->post('username')) to query against the membership table in my database so that I can retrieve the users firstname and lastname, which I believe should be done via a model called from my controller. I then need to pass that data back to my controller to use the firstname and lastname to add in to my session userdata which is set in my controller, as shown below.
$data = array(
'username' => $this->input->post('username'),
'firstname' => //need to retrieve value from database,
'lastname' => //need to retrieve value from database,
'is_logged_in' => true
);
$this->session->set_userdata($data);
Thanks,
Kristan.
In your model, make a function to retrieve the first and last name of a user:
public function get_user_details($username){
// retrieve contents from db:
// the first username here is the name of the column in your table
$query = $this->db->select('firstname, lastname')
->where('username', $username)
->get('membership');
return $query->result_array();
}
In your controller, like you were doijng, grab the POST contents in your controller:
$username = $this->input->post('username');
Then, from your controller, call your model function but save the output of that model function in a variable:
$data = $this->user_model->get_user_details($username);
After that, you can do what you were trying to do:
$this->session->set_userdata($data);
Hope that helps. I wrote this from the top of my head but it should work. I also suggest you read the CI documentation through because it really is some of the best documentation I have ever seen for a framework. Good luck.
Please check CodeIgniter user guide for model. The example of Blog controller and Blog model will answer you.
class Blogmodel extends CI_Model {
var $title = '';
var $content = '';
var $date = '';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_last_ten_entries()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
function insert_entry()
{
$this->title = $_POST['title']; // please read the below note
$this->content = $_POST['content'];
$this->date = time();
$this->db->insert('entries', $this);
}
function update_entry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->date = time();
$this->db->update('entries', $this, array('id' => $_POST['id']));
}
}
class Blog_controller extends CI_Controller {
function blog()
{
$this->load->model('Blog');
$data['query'] = $this->Blog->get_last_ten_entries();
$this->load->view('blog', $data);
}
}
You first need to create a model.
class Membership_model extends CI_Model {
function __construct() {
parent::__construct();
}
function getUser($username) {
$query = $this->db->get_where('membership', array('username' => $username));
return $query->result_array();
}
}
then in your controller, use the membership model to retrieve data. Calling this function: $this->membership_model->getUser($this->input->post('username'));