I've been encountering problems with passing variables form different views. What i want is whenever a user logs in his id, It would automatically retrieve the data that is connected to that ID from the database.
Apparently, I have 3 controllers for my login (c_home,c_login and c_verifylogin), 1 model (m_login) and 1 view (v_home)
Can anyone tell me what I am missing?
Controllers:
c_login
function index() {
$this->load->helper(array('form','html'));
$this->load->view('v_login'); //load view for login
}
c_home
function index() {
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['studentid'] = $session_data['studentid'];
$this->load->view('v_display', $data);
} else {
//If no session, redirect to login page
redirect('c_login', 'refresh');
}
}
function getGrades() {
$data['query'] = $this->m_login->result_getGrades();
$this->load->view('v_display', $data);
}
function logout() {
//remove all session data
$this->session->unset_userdata('logged_in');
$this->session->sess_destroy();
redirect('c_login', 'refresh');
}
c_verifylogin
function index() {
$this->form_validation->set_rules('studentid', 'studentid', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE) {
$this->load->view('v_login');
} else {
//Go to private area
redirect('c_home', 'refresh');
}
}
function check_database() {
//Field validation succeeded. Validate against database
$studentid = $this->input->post('studentid');
$password = $this->input->post('password');
//query the database
$result = $this->login->login($studentid, $password);
if($result) {
$sess_array = array();
foreach($result as $row) {
//create the session
$sess_array = array('studentid' => $row->studentid);
//set session with value from database
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
} else {
//if form validate false
$this->form_validation->set_message('check_database', 'Invalid username or password');
return FALSE;
}
}
m_login
function login($studentid, $password)
{
//create query to connect user login database
$this->db->select('studentid, password');
$this->db->from('users');
$this->db->where('studentid', $studentid);
$this->db->where('password', md5($password));
$this->db->limit(1);
//get query and processing
$query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result(); //if data is true
} else {
return false; //if data is wrong
}
}
function result_getGrades()
{
$this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
$this->db->from('grades');
$this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
$this->db->join('subjects','subjectblocking.subjectcode=subjects.subjectcode');
$this->db->where('studentid', '2013-F0218');
$this->db->where('sem', '1');
$this->db->where('sy','2013-2014');
$query=$this->db->get();
return $query->result();
}
Views: v_display
<!DOCTYPE html>
<head>
<title>Simple Login with CodeIgniter - Private Area</title>
</head>
<body>
<h1>Home</h1>
<h2>Welcome <?php echo $studentid; ?>!</h2>
Logout
<table class="table">
<thead>
<th>Subject Code</th>
<th>Description</th>
<th>Grade</th>
</thead>
<?php foreach ($query as $row){ ?>
<tr>
<td><?php echo $row->subjectcode;?><br></td>
<td><?php echo $row->description;?><br></td>
<td><?php echo $row->final;?><br></td>
</tr>
<?php } ?>
</table>
</body>
</html>
and the error that i have encountered is
Message: Undefined variable: query
and
Message: Invalid argument supplied for foreach()
The first thing I see is, that you don't name the table in your query:
Change:
$query = $this->db->get();
To this:
$query = $this->db->get("your_table_name_here);
When I read your code I feel headache.
You can actually just put the verify login in your c_login and not create another c_verify controller.
To make it sense
Try to refactor your code like the connection will be like this
c_home = private page that can only be access if the user is login
c_login = verify if the input of user passed and check the data from database.
To summarize
c_login will compose of this functions :
verify user input
check database through m_login
Note: Your logout should be put in the core so that all controller can use it
In your c_home, you just need to create a model that will get the data from database and pass it to your
$data['grades'] = $your_model->get_grades
the variable grades will now be pass to view using $data.
Note: You don't need to create another function to just get the data. What you only need is the model because that is the purpose of model and just pass it in your variable in your controller.
https://www.codeigniter.com/userguide3/general/
Summarize :
From Model -> Controller -> View Get data from model pass it in
controller show it in view
Related
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?
I have a function in my model that checks the credentials given in the login form. It selects the email, senha and tipo_pessoa. Below is the function:
public function find_credentials()
{
$this->db
->select('email, senha, tipo_pessoa')
->from($this->table)
->where('email', $this->input->post('email'))
->where('senha', md5($this->input->post('password')));
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
}
return false;
}
The next function, located in my Controller, is executed regardless of the results of the previous function. It decides what to do depending on the returned result:
public function validate_credentials()
{
if ($this->Usuarios_fisica_model->find_credentials()) {
$data = array();
$data['email'] = $this->input->post('email');
$this->session->set_userdata($data);
$this->session->set_flashdata('message', 'Bem-vindo!');
redirect('/', 'refresh');
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/');
}
}
I need to store tipo_pessoa in the session to determine which page the user should be redirected to. I have two different tables for two different kind of users, and each kind has its own page.
Edit*
After the suggested solutions, I added to my header file the following code to echo the tipo_pessoa:
<div class="menu_login">
<?php if ($this->session->userdata('email')) { ?>
<span><?php echo $this->session->userdata('email'); ?></span>
<span><?php echo $this->session->userdata('tipo_pessoa'); ?></span>
Ir ao Painel
Sair
<?php } else { ?>
<span>Minha Conta</span>
Entre
Cadastre-se
<?php } ?>
</div>
Use this changes in Model:
$query = $this->db->get();
return $query->result();
and make this changes to controller:
$data = $this->Usuarios_fisica_model->find_credentials();
if(!empty($data))
{
$tipo_pessoa = $data[0]['tipo_pessoa']; //Get value of tipo_pessoa
$this->session->set_userdata('tipo_pessoa', $tipo_pessoa);//Set value in session
//your if part code
}
else
{
//your else part code
}
Here's an example of how to set session data from the results of a query:
function get_something()
{
$this->db->select('something');
$something = $this->db->get('table')->row();
$this->session->set_userdata('something',$something);
}
With your example model:
$this->db
->select('email, senha, tipo_pessoa')
->from($this->table)
->where('email', $this->input->post('email'))
->where('senha', md5($this->input->post('password')));
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result_array();
}
return false;
controller:
if ($something = $this->Usuarios_fisica_model->find_credentials()) {
$data = array();
$data['email'] = $this->input->post('email');
$this->session->set_userdata('tipo_pessoa', $something['tipo_pessoa']);
$this->session->set_userdata($data);
$this->session->set_flashdata('message', 'Bem-vindo!');
redirect('/', 'refresh');
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/');
}
Instead of doing what I intended to do, I simply put a select box in the login page to choose between the two different types. Now it is easy to retrieve the value and make the choices.
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.
I hope you're doing fine. Can somebody help me with my problem? I have 2 tables. The other one is for customers, it has an auto-increment value for customer_id. The other table is for orders, it has an auto-increment also for its orders_id and a foreign key from the other table (customers).
When I insert a new customer, if it is successful, I want the page to be redirected to the add new order page. In inserting new order, the customer_id field in my orders table should have the same value as the newly added customer. Adding customer and adding new order is of different function in my controller. I am having an error 1452 when inserting the new order, which means the value inserted for the foreign key customers_id in the orders table is different with the value in the other table (customers).
Now, I've got this solution using session. My problem is the other session for getting the last id is overriding the session for logging in.
Here's some code snippets from my controller:
Class MyController extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->c_id = 0;
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
if($session_data['username'] == 'administrator'){
$this->load->database('sample');
$this->load->model('samplemodel_model');
$this->load->library('form_validation');
} else {
redirect('home', 'refresh');
}
} else {
redirect('login', 'refresh');
}
}
public function index() {
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
//code for validation here
$customers = $this->samplemodel_model->get_entries('customers');
if($this->form_validation->run() == FALSE) {
//Field validation failed.
} else {
//Insert $data
//$data = array('xxxxxx');
//data is something like that
$this->create($data);
}
}
else
{
//If there's no session it will redirect to login page
}
}
//add new orders
public function addOrders() {
if($this->session->userdata('last_inserted_id')) //if I use this session, I can get the last inserted ID but the session data for the login will not be retrieved.
{
$session_data = $this->session->userdata('last_inserted_id');
$orders = $this->samplemodel_model->get_entries('orders');
if($this->form_validation->run() == FALSE) {
//Field validation failed.
} else {
//Insert data
$data = array('customer_id' => $session_data['customer_id'],
'order_type' => $this->input->post('order_type'));
$this->createItem($data);
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
//create customer
public function create($data) {
//Insert data
$customers = $this->samplemodel_model->get_entries('customers');
//$data = array(xxxxx);
//somethin' like that for data array
$this->load->samplemodel_model->create('customers', $data);
//***********************************************************//
// get and save last id inserted //
//***********************************************************//
//query the database
$result = $this->samplemodel_model->get_last_inserted($this->db->insert_id());
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array('customer_id' => $row->customer_id);
$this->session->set_userdata('last_inserted_id', $sess_array);
}
return TRUE;
}
else
{
echo "<script type='text/javascript'>alert('error');</script>";
return false;
}
session_start('last_inserted_id');
//********************************************************//
// end //
//********************************************************//
redirect('myController/addOrders', 'refresh');
}
public function createItem($data) {
//Insert data
$orders = $this->samplemodel_model->get_entries('orders');
$data = array('customer_id' => $session_data['customer_id'],
'order_type' => $this->input->post('order_type'));
$this->load->samplemodel_model->create('orders', $data);
//I'm not so sure if it is in this function that I should place the unset for the session 'last_inserted_id'
redirect('home', 'refresh');
}
}
And in my model, I inserted another function which helps me saving the last id inserted. Here's it:
public function get_last_inserted($id)
{
$this -> db -> select('customer_id');
$this -> db -> from('customers');
$this -> db -> where('customer_id', $id);
$this -> db -> limit(1);
$query = $this -> db -> get();
if($query -> num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}
PLEEEASE! HELP :'( I would really appreciate if you have any other ideas. THANK YOU SOOOOO MUCH!
The issue is that you're redirecting, Each HTTP request is it's own process with it's own variables, and each request can't access the variables set in other requests.
Try passing the customer ID as a parameter to addOrders(), you can then use the codeigniter way of passing params around :
http://www.example.com/controller/method/paramter
Check the docs :
https://ellislab.com/codeigniter/user-guide/general/controllers.html
under the segment : Passing URI Segments to your Functions
Other possible solution : Store the customerID in the session, or in a user object you instantiate when you create a new user, but that's more dependent of the use case.
I'm new to codeigniter and php, few days only, so I need a little help.
I'm trying to put some data in my cookie from table so I can check where to redirect user after login. In table users there are two columns named Admin and Company with one or zero if user is or not, and then i wish to insert that information to cookie.
function conformation in user_controler is:
function conformation(){
$this->load->model('user');
$q = $this->user->confr();
if($q){
$data = array(
'username' => $this->input->post('username'),
'Admin' => $this->input->post($a = $this->user->getAdmin), // get 1/0 from users column Admin
'Company' => $this->input->post($c = $this->user->getComp),
'login' => true
);
if( $a == 1 ){ //is admin redirect to admin view
$this->session->set_userdata($data);
redirect('user_controler/useradm');
}
if($c == 1){ //if company redirect to company view
$this->session->set_userdata($data);
redirect('user_controler/usercomp');
}
$this->session->set_userdata($data);// if common user redirect to user view
redirect('user_controler/userpro');
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
And in user model:
function getAdmin{
$this->db->where('Admin', 1);
$a = $this->db->get('users');
}
function getComp{
$this->db->where('Company', 1);
$a = $this->db->get('users');
}
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Also have site controller for checking login
class Site extends CI_Controller{
function __construct() {
parent::__construct();
$this->login();
}
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || login != TRUE){
$this->log;
die();
}
}
}
Of course it's not working because i should probably check these column some other way but I don't know how. I Also have enabled table ci_session and it's work perfectly without Admin and Company.
Hello and welcome to Stackoverflow.
Here are my updates to the code (I have annotated my changes):
function conformation(){
$this->load->model('user');
if($this->user->confr()){ //$q wasn't needed, as you are only using this twice
$user = $this->input->post('username'); //I have added this as I will be referring to it a couple of times.
$data = array(
'username' => $user,
'Admin' => $this->user->getAdmin($user), // Your method was questioning the original form looking for data that it would never find - This will question your model.
'Company' => $this->user->getComp($user), //Same as above
'login' => true
);
$this->session->set_userdata($data); //It doesn't matter who the user is, we shall set the data to start with.
if($this->user->getAdmin($user)){ //is admin redirect to admin view
redirect('user_controler/useradm');
}
elseif($this->user->getComp($user)){ //if company redirect to company view
redirect('user_controler/usercomp');
}
else { //Redirect non-privileged users.
redirect('user_controler/userpro');
}
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
Users Model:
function getAdmin($user){
$this->db->where('username', $user); //Before you was just returning everyone who is an admin This instead finds the user
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Admin"]==1) { return true; } //This finds if the user is a admin or not, and the function will now return a value (true)
}
}
function getComp($user) {
$this->db->where('username', $user);
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Company"]==1) { return true; }
}
} //Edited similar to the function above
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Lastly your login function:
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || $login != TRUE){ //You weren't referring to your $login variable
$this->log;
die();
}
}
Hopefully this helps with your problems, let me know if you need any amendments.