Codeigniter Active Records Fatal Error - php

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
}

Related

PHP: can't insert data to database in web hosting, but in local it's working using CI

I'm writing PHP using CI. I inserted data, but got an error like this:
Code:
class Recruit extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
$this->load->model('Resume_model');
$this->load->helper(array('form','url'));
}
public function index() {
$this->data['posts'] = $this->Resume_model->get_resume();
$this->load->view('recruit', $this->data);
}
public function resume_form() {
echo 'OK';
$test = $this->input->post('type');
echo 'test:',$test;
echo 'KO';
$save = array(
'type' =>$this->input->post('type'),
'fullname' =>$this->input->post('fullname'),
'tel' =>$this->input->post('tel'),
'location' =>$this->input->post('location')
);
$this->Resume_model->saveResume($save);
redirect(base_url()."recruit");
}
Class Resume_model extends CI_Model {
function saveResume($data) {
{
$this->db->insert('resume', $data);
$resume_id = $this->db->insert_id();
}
return $resume_id;
}
function get_resume() {
$this->db->select("fullname,type");
$this->db->from('resume');
$query = $this->db->get();
return $query->result();
}
function getResume() {
$query = $this->db->query('SELECT * FROM resume');
if($query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}
public function deleteResume($id) {
$this -> db -> where('id', $id);
$this -> db -> delete('resume');
}
Make your fields in the DB to allow NULL input.
The reason is simple, your localhost environment and your online environment are different. Different MySQL configurations or different versions causes these errors.
Sometimes there is a need for putting in an empty record into a reference table for future use or because of the order of your coding event but to fix it you have to either put data into your columns upon inserting or setting your column (type) to 'NULL' or 'NULLABLE' from the DB.

converting database result into array in codeigniter

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();

Codeigniter can not redirect

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;

Calling functions from within a function [duplicate]

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.

Codeigniter - Query returns 1 row even though there is no data to match

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.

Categories