CodeIgniter model not loading correctly - php

I am writting my first CodeIgniter script and I can't get the following model to load, if anyone could maybe help me?
Here is my controller file:
public function process(){
// Load the model
$this->load->model('users/login', 'users');
// Validate the user can login
$result = $this->users->validate();
// Now we verify the result
if(!$result){
// If user did not validate, then show them login page again
$this->index();
}else{
// If user did validate,
// Send them to members area
redirect('home');
}
}
And here is my model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_Model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function validate(){
// grab user input
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
// Prep the query
$this->db->where('username', $username);
$this->db->where('password', $password);
// Run the query
$query = $this->db->get('users');
// Let's check if there are any results
if($query->num_rows == 1)
{
// If there is a user, then create session data
$row = $query->row();
$data = array(
'userid' => $row->userid,
'fname' => $row->fname,
'lname' => $row->lname,
'username' => $row->username,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
// If the previous process did not validate
// then return false.
return false;
}
}
?>
I can confirm the the process function is loading however any code that goes underneath the $results = $result = $this->users->validate(); doesn't appear. The model is also loading, it is as soon as I try call a function, the script kills itself.
Sorry if this question is a little bland.
Thanks
Peter

It all came down to my code. Your models class name must be equal to the name of the model file.
So in this case, I should have named my file login_model.php and then the class itself must be called Login_model (the first character must be uppercase, all other characters must be lowercase). When calling the model in the controller it must all be lower case like:
$this->load->model('login_model');
Hope this is help to anyone in the future, thanks to all for the efforts and comments :)

You try capitalize the name of your file?
user_model.php to User_model.php?

Related

login page is not working in codeigniter

Please help me.
I'm trying to create login system using codeIgniter. but i still cannot pass the login form even the value is true such as the value in the database. please help me to fix and figure out whats wrong with this.
This is database structure. Username : jeff_way and Password : jeff_way (note : encripted using md5)
This is the Login controller
<?php session_start();
class Login extends CI_Controller{
function index()
{
/*$data['main_content']='tampilan';*/
$this->load->view('tampilan');
}
function validate_credentials()
{
var_dump(session_id('is_logged_in'));
var_dump($_POST);
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query)
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' =>true
);
$this->session->set_userdata($data);
redirect('site/members_area');
}
else
{
$this->index();
}
}
this is the model :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
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;
}
}
Here is the login form view :
<div class="input-group container-fluid jumbotron shadow">
<h2>Login Fool</h2>
<?php echo form_open('login/validate_credentials');?>
<?php echo form_input(['name'=>'username', 'class'=>'form-control jarak','placeholder'=>'Username']);?>
<?php echo form_password(['name'=>'password', 'class'=>'form-control jarak','placeholder'=>'Password']);?>
<?php echo form_submit(['class'=>'btn btn-default jarak','value'=>'Login']);?>
<?php echo anchor('login/sign_up','Create Account',array('class'=>'btn btn-info jarak'));?>
<?php form_close();?>
everytime i try to login, the page always sent to controller login/validate_credentrial. here is the picture :
but when i try to use var_dump($_POST) on login, it sends value.
Please help me. thanks
The reason why you are seeing /login/validate_credentials is because you are telling it to.
If you picture this... you originally display the form via /login.
When you submit the form it calls (goes to) the url /login/validate_credentials as defined in your forms action.
In the case the login credentials do not match your database, i.e. fails, then this causes the validate_credentials() method to call $this->index which simply redisplays the form. It does not alter the url.
So the resulting url will remain /login/validate_credentials.
If you are expecting to see /login as the url, then you will need to perform a redirect('login'); instead.
A note on the validate() function
In regards to the model method validate()...
If you are going to return a value, your function should always return a value under all conditions.
So you should have something like...
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;
}
return FALSE; // else we need to specifically return FALSE
}
UPDATE: Debug Code Added
function validate() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('membership');
echo $this->db->last_query(); // DEBUG the SQL
echo $query->num_rows; // DEBUG how many rows
if ($query->num_rows == 1) {
return TRUE;
}
return FALSE;
}
What debug info do you get from the above?

how to send data from controller to model with CodeIgniter

i'm newbie with CI and i'm using CI v.2.2.1, i want send data from my controller to model but i have some trouble here. The error said my model is undefined property. here's my code :
Controller :
users.php
public function postUser(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
$phone = $this->input->post('phone');
$address = $this->input->post('address');
$level = $this->input->post('level');
$status = $this->input->post('status');
$this->load->model('model_crud');
$query = $this->model_crud->insert('Users',$_POST);
echo "$query";
}
Model :
model_crud.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_crud extends CI_Model {
public function __construct(){
parent::__construct();
}
public function insert($table,$data){
$query = $this->db->insert($table,$data);
return $query;
}
}
is there any configuration to use model or my code is wrong?
can anyone help me ? Thx
1st thing, you're not providing enough information about the error.
Is the model loaded anywhere/anyhow? From the controller you load your model this way:
$this->load->model('model_crud');
Or you can preload it, by modifying your autolad.php config file
in postUser() - you're getting your post data, but don't really use it. Instead, you're passing the whole global $_POST, which may be dirty and unsafe. I'd recommend using CodeIgniter's XSS filtering when forming a data array from POST:
$data = array (
'username' => $this->input->post('username', TRUE); //TRUE identifies you're passing your data through XSS filter,
//all other elements
);
finally:
$query = $this->model_crud->insert('Users',$data);
You can do it by sending an array to your model with table columns name as key :
Controller :
$data = array(
'username' => $this->input->post('username') ,
'password ' => $this->input->post('password') ,
...
);
// 'TABLE COLUMN NAME' => "VALUE"
$query = $this->model_crud->insert('Users',$data);
echo "$query";

How to Update Data in CodeIgniter?

First, sorry for my bad english, if you don't understand what I'm saying, you can ask for it and I will search for another suitable and precise words.
Now, I've been working with codeigniter in this last 2 weeks, so I got so many question for it, but I found 1 which is hanging on my mind.
I started with simple CRUD, then make it advanced, it's good so far, until I got stuck while updating data. When I click the "submit" button, I get only 404 page. And when I see the database, nothing change.
Here's the controller's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Master_user extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('mod_master_user');
$this->load->library('datatables');
}
public function index(){
if ($this->session->userdata('type') == 'admin') {
$data['hasil'] = $this->mod_master_user->getall();
$datum['content'] = $this->load>view('master_user/view',$data,true);
$this->load->view('main',$datum);
} else if ($this->session->userdata('type') == 'user'){
$a= $this->load->model('m_absensi');
$aa["content"] = $this->load->view('absensi/form',$a,true);
$this->load->view("absensi/mainUser",$aa);
}
}
public function tambah_data(){
if($this->input->post('nama')){
$this->mod_master_user->tambah();
redirect('master_user');
}else{
$this->load->view('master_user/add');
}
}
public function update_data($id_user)**//i use this method for updating data**{
if($this->input->post('submit')){
$this->mod_master_user->update($id_user);
redirect('master_user/index');
}
$data['hasil']=$this->mod_master_user->getById($id_user);
$this->load->view('master_user/edit',$data);
}
public function delete_data($id_user){
$this->mod_master_user->delete($id_user);
redirect('master_user');
}
public function error()
{
$this->output->set_status_header('404');
$data['content'] = '404';
$this->load->view('master_user/404',$data);
}
public function print_report()
{
$this->load->view('master_user/print');
}
public function jam_masuk()
{
$this->load->view('master_user/jam_masuk');
}
}
Here comes the model's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Mod_master_user extends CI_Model{
var $tabel_name = 'master_user';
function __construct() {
parent::__construct();
}
public function getall(){
$ambil_data = $this->db->get('master_user');//mengambil tabel master_user
if ($ambil_data->num_rows() > 0 ){ //jika data lebih dari 0
foreach ($ambil_data->result() as $data){
$hasil[] = $data;
}
return $hasil;
}
}
public function tambah(){
$id_user = $this->input->post('id_user');
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$tanggal_lahir = $this->input->post('tanggal_lahir');
$tempat_lahir = $this->input->post('tempat_lahir');
$role = $this->input->post('role');
$data = array (
'id_user'=> $id_user,
'nama'=>$nama,
'password'=>md5($password),
'tanggal_lahir'=>date('Y-m-d',strtotime($tanggal_lahir)),
'tempat_lahir'=>$tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->insert('master_user', $data);
}
public function update($id_user)**//i use this method to updating data**{
$id_user=$this->input->post('id_user');
$nama=$this->input->post('nama');
$password=$this->input->post('password');
$tanggal_lahir=$this->input->post('tanggal_lahir');
$tempat_lahir=$this->input->post('tempat_lahir');
$role=$this->input->post('role');
$data = array (
'id_user' => $id_user,
'nama' => $nama,
'password'=> $password,
'tanggal_lahir'=> $tanggal_lahir,
'tempat_lahir'=> $tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->update('master_user',$data); //update data
}
public function getById($id_user){ //mengambil data dari db berdasarkan id (primary key)
return $this->db->get_where('master_user',array('id_user'=>$id_user))->row();
}
public function delete($id_user){
$this->db->where('id_user',$id_user);
$this->db->delete('master_user'); //query delete data
}
public function cek_user_login($username, $password) {
$this->db->select('*');
$this->db->where('NAMA', $username);
$this->db->where('PASSWORD', md5($password));
$query = $this->db->get($this->tabel_name, 1);
if ($query->num_rows() == 1) {
$this->db->limit(1);
return $query->row_array();
}
}
public function validasi()
{
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$check = $this->mod_master_user->check($nama, md5($password));
if($check->num_rows() > 0)
{
//login berhasil, buat session
//$this->session->set_userdata('username',$username);
redirect('master_user');
}
else
{
//login gagal
//$this->session->set_flashdata('message','Username atau password salah');
redirect('users');
}
}
}
So far, I get no answer on other forums, so I asked for the answer here :)
Any answer/help will be appreciated. Thank you :)
It's been some time since I used CodeIgniter.
Are you loading the input class? so you can actually receive $_GET and $_POST data? I think it does this by default actually.
This might be a bit too simple, but are you calling the right URI and are you sure its reaching your view??
Might help to see your view, are you using the form helper for this? https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html
If you get 404, then the problem is in your form action tag. It means it doesn't post to the right url.
This is most likely (if not surely) due to a bad route.
In config/routes.php, you need a route like: $route['master_user/update/(:any)'] = 'master_user/update_data/$1;
And in your view you would need a form with the action pointing to that route, such as:
<form action="master_user/update_data/1">
<!-- your fields and submit button -->
</form>
Where the number 1 (in the action url) is the id of the register being updated.

Codeigniter Inputting session data from model for a simple authentication system

Trying to put together a simple login authentication. Been at this for quite sometime, and I can't find where I'm going wrong. Pretty new to Codeigniter and OOP PHP. I know there are authentication libraries out there, but I'm not interested in using those.
Model:
function login($username, $password){
if ($this->db->table_exists($username)){
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get($username);
if($query->num_rows >= 1)
{
return true;
$data = array(
'username' => $this->input->post('username'),
'login' => true
);
$this->session->set_userdata($data);
}
}
}
Controller
function __construct(){
parent::__construct();
$this->logincheck();
}
public function logincheck(){
if ($this->session->userdata('login')){
redirect('/members');
}
}
If I just echo from the controller: $this->session->all_userdata(); I get an empty array. So the problem seems to be that the $data array in the model isn't being stored in the session.
This code is part of your problem. You're asking the database driver if a table with the same name as the username exists, and also trying to get the username and password from the same table.
if ($this->db->table_exists($username)){
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get($username);
Change the $username in $this->db->table_exists($username); and $this->db->get($username); to whatever table your users are in.
I am guessing your login function is the issue:
if ($this->db->table_exists($username)){
This just doesn't look right... If your user name was admin, there there would need to be an admin table, etc... I am posting a quick example I recently wrote that seems to get the job done:
public function doLogin(){
$this->db->select('user_pass,user_id');
$query = $this->db->get_where('users', array('user_name' => $this->input->post('login')));
if($query->num_rows<1 || $query->row('user_pass')!=md5($this->input->post('password')))
return false;
$this->session->set_userdata(array('loggedin'=>true,'user_id'=>$query->row('user_id')));
return true;
}

hashing/salting post data codeigniter

I am at the tail end of signing in a created user to an account. I've commented out my flow and everything seems to make since, however I am missing a step or two because now the post data password is not being hashed.
CONTROLLER:
function validate_credentials()
{
// WHEN THE VIEW IS LOADED THIS FUNCTION IS CALLED AND LOADS MODEL AS WELL AS DEFINES THE SALT VARIABLE AND LOADS THE ENCRYPTING HELPER LIBRARY
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
$salt = $this->_salt();
$this->load->library('encrypt');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->encrypt->sha1($user->salt. $this->encrypt->sha1($this->input->post('password')))
);
$user = $this->um->validate($data);
}
// IF ITS A REAL USER OPEN THE GATE AND LET THEM IN
if($user)
{
$this->session->set_userdata($data);
redirect('account/dashboard');
}
else
{
$this->index();
}
}
MODEL:
function validate($data)
{
$this->output->enable_profiler(TRUE);
// TAKING THE DATA FROM THE MODEL AND CHECKING IT AGAINST THE STORED INFO IN THE DB
$query = $this->db->where($data)->get('users', 1);
if($query->row())
{
return $query->row();
}
}
thanks in advance
$user->salt should just be $salt.

Categories