I am new to CodeIgniter and experiencing the following error after creating new model for the purpose of user dashboard in addition to admin dashbaord. It is really great if some one can help me. I checked previous answers in the StackOverflow but none helped me.
I am experiencing following error.
Code segment relevant to the error is as follows.
Model code
<?php
//Details of queries whicha re used to interact with teh database
class Queries extends CI_Model {
//Created a function with the name getRoles
public function getRoles() {
//Fetch the reocrds from the table
$roles = $this->db->get('tbl_roles');
if ($roles->num_rows() > 0) {
return $roles->result();
}
}
//Created a function with the name getColleges
//Used to list collge names in addcodmin view page
public function getColleges() {
//Fetch the reocrds from the table
$colleges = $this->db->get('tbl_college');
if ($colleges->num_rows() > 0) {
return $colleges->result();
}
}
public function registerAdmin($data) {
return $this->db->insert('tbl_users', $data);
}
//create function to check whther three is a admin or not...if not only
// that add admin button will be appered
public function checkAdminExist() {
$checkAdmin = $this->db->where(['role_id' => '1'])->get('tbl_users');
if ($checkAdmin->num_rows() > 0) {
return $checkAdmin->num_rows();
}
}
//Create function to check the entered email and password existance
public function adminExist($email, $password) {
$checkAdmin = $this->db->where(['email' => $email, 'password' => $password])->get('tbl_users');
if ($checkAdmin->num_rows() > 0) {
return $checkAdmin->row();
}
}
//Created function makeCollege and return value and
public function makeCollege($data) {
//if value is 0 - and 1 - if the data get inserted into the table
return $this->db->insert('tbl_college', $data);
}
//Created function register coadmin fot coadmin query called and passing data to the admin.php
//used insert method of the db class if inserted value 1 and if not value 0
public function registerCoadmin($data) {
return $this->db->insert('tbl_users', $data);
}
//qruery to display all the colleges and details in teh dashboard
public function viewAllColleges() {
//get data from differendt table and view them in one single table
$this->db->select(['tbl_users.user_id', 'tbl_users.email', 'tbl_college.college_id',
'tbl_users.username', 'tbl_users.gender', 'tbl_college.collegename',
'tbl_college.branch', 'tbl_roles.rolename']);
$this->db->from('tbl_college');
$this->db->join('tbl_users', 'tbl_users.college_id = tbl_college.college_id');
$this->db->join('tbl_roles', 'tbl_roles.role_id = tbl_users.role_id');
//get the details and return details
$users = $this->db->get();
return $users->result();
}
public function insertStudent($data) {
return $this->db->insert('tbl_student', $data);
}
public function getStudents($college_id) {
//select fields required to diaply from the college and the student table
$this->db->select(['tbl_student.id', 'tbl_college.collegename', 'tbl_student.studentname',
'tbl_student.gender', 'tbl_student.email', 'tbl_student.course']);
//Common fileds in the both the table
$this->db->from('tbl_student');
$this->db->join('tbl_college', 'tbl_college.college_id = tbl_student.college_id');
//Take only stuednts who has college id (Get the details of all the students with the college id of 3)
$this->db->where(['tbl_student.college_id' => $college_id]);
$students = $this->db->get();
return $students->result();
}
public function getStudentRecord($id) {
$this->db->select(['tbl_college.college_id', 'tbl_college.collegename',
'tbl_student.id', 'tbl_student.email', 'tbl_student.gender', 'tbl_student.studentname',
'tbl_student.course']);
$this->db->from('tbl_student');
$this->db->join('tbl_college', 'tbl_college.college_id = tbl_student.college_id');
$this->db->where(['tbl_student.id' => $id]);
$student = $this->db->get();
return $student->row();
}
public function upgradeStudent($data, $id) {
return $this->db->where('id', $id)
->update('tbl_student', $data);
}
public function removeStudent($id) {
return $this->db->delete('tbl_student', ['id' => $id]);
}
}
?>
Controller code 1
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends MY_Controller {
public function dashbaord() {
$this->load->model('queries');
//$college_id=$this->session->userdata('college_id';
$students = $this->queries->getStudents($college_id);
$this->load->view('users',['students'=>$students]);
}
}
Controller code 2
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends MY_Controller {
public function index() {
//New function to display add admin button
//and commented the existing code of $this->load->view('home');
$this->load->model('queries');
$checkAdminExist = $this->queries->checkAdminExist();
$this->load->view('home', ['checkAdminExist' => $checkAdminExist]);
//
}
public function adminRegister() {
//loading teh queries model
$this->load->model('queries');
//Calling the getRoles function inside the roles
//$roles holds the data of 2 records availble in the roles table
$roles = $this->queries->getRoles();
// print_r($roles);
// exit();
// $this->load->view('register');
//Pass this to an register view in type of an array and pass the data to register view
$this->load->view('register', ['roles' => $roles]);
}
public function adminSignup() {
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('role_id', 'Role', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('confpwd', 'Password Again', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">', '</div>');
if ($this->form_validation->run()) {
$data = $this->input->post();
$data['password'] = sha1($this->input->post('password'));
$data['confpwd'] = sha1($this->input->post('confpwd'));
$this->load->model('queries');
if ($this->queries->registerAdmin($data)) {
$this->session->set_flashdata('message', 'Admin Registered Sucessfully');
return redirect("welcome/adminRegister");
} else {
$this->session->set_flashdata('message', 'Failed to Register Admin!');
return redirect("welcome/adminRegister");
}
// echo '<pre>';
// print_r($data);
// echo '<pre>';
// exit();
} else {
echo $this->adminRegister();
}
}
//Create new view for login function in teh welcome controllder
public function login() {
//restrict the acess of the login page of welcome controller
if ($this->session->userdata("user_id"))
//redirecting to the dash board page
return redirect("admin/dashboard");
//End
$this->load->view('login');
}
public function Signin() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">', '</div>');
if ($this->form_validation->run()) {
$email = $this->input->post('email');
$password = sha1($this->input->post('password'));
$this->load->model('queries');
$userExist = $this->queries->adminExist($email, $password);
echo '<pre>';
print_r($userExist);
echo '<pre>';
//information saved in the session data will be accesed when teh user loged into the system
//inside if the yser id exists user details will be stored inside the session
if ($userExist) {
if ($userExist->user_id == '1') {
$sessionData = [
'user_id' => $userExist->user_id,
'username' => $userExist->username,
'email' => $userExist->email,
'role_id' => $userExist->role_id,
];
//redirect to teh dash board upon giving teh correct user id and password
//settin user data to the dashboard
$this->session->set_userdata($sessionData);
return redirect("admin/dashboard");
//if the coadmin login session creatiion whos id is grater than 1
} else if ($userExist->user_id > '1') {
$sessionData = [
'user_id' => $userExist->user_id,
'username' => $userExist->username,
'email' => $userExist->email,
//'college_id' => $userExist->college_id,
'role_id' => $userExist->role_id,
];
//redirect to teh dash board upon giving teh correct user id and password
//settin user data to the dashboard
$this->session->set_userdata($sessionData);
return redirect("users/dashboard");
}
} else {
$this->session->set_flashdata('message', 'Email or password is incorrect');
return redirect("welcome/login");
}
} else {
$this->login();
}
}
//crerate logout function for the user to logout
public function logout() {
//closing teh session inside logout function usinhg the userid
$this->session->unset_userdata("user_id");
return redirect("welcome/login");
}
}
View
<?php include("inc/header.php"); ?>
<div class="container">
<h3>COADMIN DASHBOARD</h3>
<?php
// echo $username = $this->session->userdata('username');
$username = $this->session->userdata('username');
?>
<h5>Welcome <?php echo $username; ?></h5>
<hr>
<div class="row">
<table class="table table-hover">
<thead>
<th scope="col">ID</th>
<th scope="col">Student Name</th>
<th scope="col">College Name</th>
<th scope="col">Email</th>
<th scope="col">Gender</th>
<th scope="col">Course</th>
</thead>
<tbody>
<!-- if users contain the data-->
<?php //if (count($students)): ?>
<!-- Iterate the array to show he records-->
<?php //foreach ($$students as $student): ?>
<tr class="table-active">
<td><?php //echo $student->id; ?></td>
<td><?php //echo $student->studentname; ?></td>
<td><?php //echo $student->collegename; ?></td>
<td><?php //echo $student->email; ?></td>
<td><?php //echo $student->gender; ?></td>
<td><?php //echo $student->course; ?></td>
</tr>
<?php //endforeach; ?>
<?php //else: ?>
<!-- If count is 0 table will not display any data-->
<tr>
<td>No records found!</td>
</tr>
<?php //endif; ?>
</tbody>
</table>
</div>
</div>
<?php include("inc/footer.php"); ?>
Any help will be highly appreciated. Thanks in advance.
Related
I am new in CI and I have make login system but I am trying to show user profile data in username and email are show on user profile view page. I am to much try but I cant solve this issue. Here is my code.
Can one tell me about how to show user profile data in profile view page? I have too much trying but no solution is available for showing a user profile data in codeigniter.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UserLogin extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper(array('form', 'url'));
$this->load->model('login_model');
}
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->view('UserLoginPage');
}
public function userLoginProcess()
{
// $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
// echo "login reached";
$this->form_validation->set_rules('username', 'Username', 'required|alpha|trim');
$this->form_validation->set_rules('password', 'Password','required');
$this->form_validation->set_error_delimiters("<p class='text-danger'>","</p>");
$this->session->set_flashdata("<p class='text-danger'>","</p>");
if ($this->form_validation->run() ){
//username aur password araha hay
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('login_model');
//$loginObj session ko check variable haa..!
$loginObj = $this->login_model->login_valid($username,$password);
if($loginObj){
// print_r($loginObj->password);
$this->session->set_userdata('userSessionObj', $loginObj);
//print_r($loginObj);
$this->load->view('userDashboard');
}
else{
// echo "<script>alert('UserName And Passowrd Are Wrong....!!!! ');</script>";
// $this->session->set_flashdata('error', 'Invalid Username and Password');
$this->load->view('UserLoginPage');
// echo "<script language=\"javascript\">alert('Username And Password Are Worng');</script>";
$this->session->set_flashdata('error','<p class="text-danger"> you entered invalid username and password');
} // end of else
} // end of public function
else
{
$this->load->view('userLoginPage');
} // end of else
} //end of function
//logout function Start
public function logout()
{
$this->session->sess_destroy();
$this->session->unset_userdata('username','password');
return redirect("userLogin");
}
//logout function End
public function register()
{
$this->load->view('registered');
} //end of register function
public function preRegister()
{
$this->form_validation->set_rules('username', 'Username', 'required|alpha|trim|min_length[5]|max_length[12]|is_unique[user.username]');
$this->form_validation->set_rules('email', 'email','required|valid_email|is_unique[user.email]');
$this->form_validation->set_rules('password', 'Password','required');
$this->form_validation->set_rules('confirmpassword', 'ConfirmPassword','required|matches[password]');
$this->form_validation->set_error_delimiters("<p class='text-danger'>","</p>");
if($this->form_validation->run())
{
$store = array(
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'dateOfbirth' => $this->input->post('dateOfbirth'),
'password' => $this->input->post('password'),
'confirmpassword'=> $this->input->post('confirmpassword'),
'gender' => $this->input->post('gender')
);
$this->login_model->insert_mod($store);
redirect('UserLogin/index');
} // end of if form_validation
else
{
$this->load->view('registered');
} // end of else
} //end of preRegister function
public function employess() // employes of add ka page view kr rha haaaa
{
$this->load->view('userDashboard');
} // employes of add ka page view kr rha haaaa
public function proEmployess()
{
// $this->load->view('addEmployess');
// $this->load->view('addEmployess');
$employessData = array(
// 'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'address' => $this->input->post('address'),
'department' => $this->input->post('department')
);
$this->login_model->employess_add($employessData);
redirect('UserLogin/employess');
}
public function myProfile(){
// $myProfile = $this->session->userdata();
$this->load->view('headerDashboard.php');
$myProfiledata ['profiles'] = $this->login_model->profileVeiw();
$this->load->view('myProfileView', $myProfiledata);
$this->load->view('footerDashboard.php');
}
// public function myProfile(){
//
// $this->load->view('headerDashboard');
// //$myProfiledata ['datas'] = $this->login_model->veiw_Employess();
// //$employessRecord['datas'] = $this->login_model->veiw_Employess();
// $this->load->view('myProfileView');
// $this->load->view('footerDashboard');
//
// }
}
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_model extends CI_Model{
public function login_valid($username ,$password)
{
$q = $this->db->where(['username'=>$username, 'password'=>$password])
->get('user');
if( $q->num_rows() )
{
//return pori row ho rhe ha jo database sa arhe haaa
return $q->row();
// return $q->row()->id;
// return TRUE;
}
else
{
return FALSE;
}
}
public function insert_mod($store)
{
$this->db->insert('user', $store);
}
public function employess_add($employessData)
{
$this->db->insert('employessRecord',$employessData);
}
public function view_employess(){
$query = $this->db->get('employessrecord');
return $query;
}public function profileVeiw(){
$queries = $this->db->get('user');
//$queries = $this->session->userdata();
// print_r($queries);
return $queries;
}
}
<div class="col-xl-6">
<div class="card" >
<div class="card-header">
<h4>Profile Details</h4>
</div><br>
<?php foreach($profiles->result() as $profile):?>
<div class="col-md-8">
<label for="name">Username:</label>
<?php echo $profile->username;?>
</div><br><br>
<div class="col-md-8">
<label for="address">Email:</label>
<?php echo $profile->email;?>
</div><br><br>
<div class="col-md-8">
<label for="address">Passowrd:</label>
<?php echo $profile->password;?>
</div><br><br>
<div class="col-md-8">
<label for="address">Gender:</label>
<?php echo $profile->gender;?>
</div><br><br>
<?php endforeach; ?>
</div>
</div>
There is opening tag php tag
so you received the data from form and inserted it in database $this->login_model->insert_mod($store) .
when you call myProfile function you get data in $myProfiledata ['profiles'] = $this->login_model->profileVeiw(); here and passed it to view. if this is correct then first try to print $myProfiledata before passing to the view if everything ok there then try to print $profiles on the "myProfileView" view.
$this->session->userdata('userSessionObj');
here you can check the session data
Edit: Some naming had been mixed up in my attempts to solve it myself. I've fixed the callback etc naming and the same error persists.
I am attempting to create a login page for my codeigniter website. I already have a registration page that correctly inputs usernames and passwords in to a "users" table. I am having issues understanding the syntax of creating the functions needed for custom form validators.
My error is "Unable to access an error message corresponding to your field name" for the password and username custom validators.
Here is the relevant part of the controller "login_ctrl"
class login_ctrl extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('login_mdl');
}
function index() {
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_userCorrect');
//Validating Password Field
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_passwordCorrect');
//variables to pass form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//reload login page if validation fails
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
} else {
//functions for custom validation
function userCorrect($username) {
$this->load->library('form_validation');
//the loads the model that contains the function to compare input to database data
$userExists = $this->login_mdl->userExists($username);
if ($userExists) {
$this->form_validation->set_message(
'userCorrect', 'correct user.'
);
return true;
} else {
$this->form_validation->set_message(
'userCorrect', 'not a valid user name.'
);
return false;
}
}
function passwordCorrect($password) {
$this->load->library('form_validation');
$passwordExists = $this->login_mdl->passwordCorrect($password);
if ($passwordExists) {
$this->form_validation->set_message('passwordCorrect', 'correct password.');
return true;
} else {
$this->form_validation->set_message('passwordCorrect', 'invalid password.');
return false;
}
}
This is the corresponding view "login"
<?php echo form_open('login_ctrl'); ?>
<h1>Login</h1><hr/>
<?php if (isset($message)) { ?>
<?php } ?>
<?php echo form_label('User Name :'); ?> <?php echo form_error('username'); ?><br />
<?php echo form_input(array('id' => 'username', 'name' => 'username')); ?><br />
<?php echo form_label('Password :'); ?> <?php echo form_error('password'); ?><br />
<?php echo form_input(array('id' => 'password', 'name' => 'password')); ?><br />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
Finally, this is the corresponding model "login_mdl" (I think the issue might be in this guy).
<?php
class login_mdl extends CI_Model{
function __construct() {
parent::__construct();
}
function userExists($username) {
$this->db->select('id');
$this->db->where('username', $username);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
function passwordCorrect($password) {
$this->db->select('password');
$this->db->where('username', $username);
$query = $this->db->get('users');
$result = $query->row();
return $result->password;
if ('password' == $password) {
return true;
} else {
return false;
}
}
}
?>
I think my issue is related to the db calls and if statements but I've been reading documentation and failing at fixing this for hours so a new pair of eyes would be greatly appreciated.
You need to make your fieldname on your costume rules function is same as your function callback. So, it’s should be like this :
$this->form_validation->set_message(
'userCorrect', 'correct user.'
Do same thing on your other function.
I am facing problem in function profile(). In this method I am fetching data from email using session.
When I login, displaying current data. But when I click on profile it displays previous session data and after refresh it become current session data.
last session data
after refresh display current session
my controller file is admin.php.
admin.php
<?php
class Admin extends CI_Controller{
function __construct(){
parent::__construct();
// Load form helper library
$this->load->helper('form');
//Load foam valodation library
$this->load->library('form_validation');
// Load the model
$this->load->model('adminmodel');
}
public function index(){
// Load our view to be displayed
$this->load->view('admin/login');
}
// Check for Admin login process
public function dashboard(){
// Validate the user can login
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) //checking validation
{
if(isset($this->session->userdata['logged_in']))
{
$this->load->view('admin/dashboard');
}
else
{
$this->load->view('admin/login');
}
}
else
{ //validation are true
if (isset($_POST['login']))
{
$email = $this->input->post('email');
$password =$this->input->post('password');
// Validate the admin can login
$result = $this->adminmodel->validate($email,$password);
if ($result) {//if the user credidential is validated
$data = array(
'email' => $this->input->post('email'),
'is_logged_in' => true
);
print_r($data);
}
// Add user data in session
$this->session->set_userdata($data);
//load dashboard and passing value
$this->load->view('admin/dashboard',$result);
}
}
} //end of dashboard
public function profile(){
if($this->session->userdata('is_logged_in')){
$email = $this->session->userdata('email');
$result = $this->adminmodel->fetchdata($email);
print_r($result);
$this->load->view('admin/profile',$result);
}
else
{
echo "failed profile";
}
} // end of profile
// Logout from admin page
public function logout() {
// Removing session data
$sess_array = array(
'email' => '',
'is_logged_in'=>false
);
$this->session->unset_userdata($sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('admin/login', $data);
}
}
?>
model file
adminmodel.php
<?php
class Adminmodel extends CI_Model{
public function validate($email,$password)
{
$query = $this->db->where(['email'=>$email,'password'=>$password])
->from('login')
->get();
$result = $query->row();
return $result;
}
public function fetchdata($email)
{
$query = $this->db->where(['email'=>$email])
->from('login')
->get();
$result = $query->row();
return $result;
}
}
profile.php
<?php
echo " I am in Profile " . $email;
?>
<!DOCTYPE html>
<html>
<head>
<title>Profile</title>
</head>
<body>
<p>Name : <input type = "text" value="<?php echo $name; ?>" /><p>
<p>Mobile : <input type = "text" value="<?php echo $mobile; ?>" /> </p>
<p>Address : <input type = "text" value="<?php echo $address; ?>" /> </p>
<p>Email : <input type = "text" value=" <?php echo $email;?>" /> </p>
</body>
</html>
Try the following, after logount instead of unset data, destroy the session entirely
$this->session->sess_destroy();
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
im working on a project at the moment that allows users to register and log into there own user area and add/edit/delete note snippets.
Im currently working on the edit class and im wondering how can i make it so that other users cant visit the same url and edit someones note? (all notes are stored in the same table in the database)
schema = id, title, description, snippet, user_id
for example if user1 wants to edit his note at http://domain.com/edit/1 (which is bound to his user_id in the database) how can i stop user2 from visiting that same url and editing his note?
here is the controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Mysnippets extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/login/');
}
$this->load->model('dashboard_model');
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username']= $this->tank_auth->get_username();
}
public function index()
{
$this->data['private_snippets'] = $this->dashboard_model->private_snippets();
$this->load->view('dashboard/my_snippets', $this->data);
}
function edit_snippet($snippet_id) {
$snippet = $this->dashboard_model->get_snippet($snippet_id);
//validate form input
$this->form_validation->set_rules('title', 'Title', 'required');
if (isset($_POST) && !empty($_POST))
{
$data = array(
'title' => $this->input->post('title'),
);
if ($this->form_validation->run() === true)
{
$this->dashboard_model->update_snippet($snippet_id, $data);
$this->session->set_flashdata('message', "<p>Product updated successfully.</p>");
redirect(base_url().'mysnippets/edit_snippet/'.$snippet_id);
}
}
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['snippet'] = $snippet;
//display the edit product form
$this->data['title'] = array(
'name' => 'title',
'type' => 'text',
'value' => $this->form_validation->set_value('title', $snippet['title']),
);
$this->load->view('dashboard/edit_snippet', $this->data);
}
}
heres the model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Dashboard_model extends CI_Model {
public function public_snippets()
{
$this->db->select('id, title, description, author, date_submitted');
$query = $this->db->get_where('snippets', array('state' => 'public'));
return $query->result_array();
}
public function private_snippets()
{
$this->db->select('id, title, description, date_submitted');
$query = $this->db->get_where('snippets', array('user_id' => $this->tank_auth->get_user_id()));
return $query->result_array();
}
public function add_snippet($data)
{
$this->db->insert('snippets', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function get_snippet($snippet_id) {
$this->db->select('id, title');
$this->db->where('id', $snippet_id);
$query = $this->db->get('snippets');
return $query->row_array();
}
public function update_snippet($snippet_id, $data)
{
$this->db->where('id', $snippet_id);
$this->db->update('snippets', $data);
}
}
heres the view:
<?php echo $message;?>
<?php $snippet_id = $snippet['id']; ?>
<?php echo form_open("mysnippets/edit_snippet/$snippet_id");?>
<?php echo form_input($title); ?>
<?php echo form_submit('submit', 'Submit');?>
<?php echo form_close(); ?>
is there a way i can restrict it so if another user tried to go to that url i can redirect them or show a error message
Something like this might work.
public function edit_snippet(snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
// this depends on what you are using for sessions;
// recommend you use db sessions
if($snippet->user_id != $this->session->userdata('user_id');)
{
redirect('/mysnippets');
}
else
{
//allow editing
You could check whether the id you are editing is the same as the session id provided when you have logged in.
it could be something like :
if ($snippet_id != $this->session->userdata('login_id'))
{
//redirect to another page
}
I would just add a line to the following function in the model:
public function get_snippet($snippet_id) {
$this->db->select('id, title');
$this->db->where('id', $snippet_id);
//users can access only their own snippets
$this->db->where('user_id', $this->session->userdata('user_id'));
$query = $this->db->get('snippets');
return $query->row_array();
}
That prevents them from accessing the information, but I'd do something to prevent them from even being able to try in the first place, i.e. not giving them the choice.