Saving user ID to database using CodeIgniter - php

I am trying to create an application with which users can enrol on to a course. To enrol a user has to be approved by the admin. A user will select a course by clicking on a course,then the course ID and the user ID should get saved in a database. However I can't get the user ID to save in a database. I have added the user ID as a part of the session. So how can I save the user ID which is now in the session?
Here is the model:
public function select_course()
{
$data['users_id']=$this->input->post($this->session->userdata('users_id'));
$query =$this->db->insert('gp_approval_course',$data);
if ($query)
{
return true;
}
else
{
return false;
}
}
Here is the controller:
public function add_course()
{
$this->load->model('model_users');
if ($this->model_users->select_course())
{
echo "You have selected a course to enroll on to!";
echo ($this->session->userdata('users_id'));
return true;
}
else
{
echo "Database problem";
return false;
}
}

change
$data['users_id']=$this->input->post($this->session->userdata('users_id'));
to
$data['users_id']=$this->session->userdata('users_id');
$data['course_id'] = $this->input->post('your_course_id_var');

Related

Codeigniter 3: update Sql table column via GET superglobal

I am working on a Register and Login application with CodeIgniter 3 and Bootstrap.
In my "users" table I have an "active" column that can take either 0 or 1 as value.
I want to be able to change the value of the "active" column corresponding to a user from 0 to 1 (activate the user) by clicking a link in my users view:
The "Activate" button code in the users view:
<span class="glyphicon glyphicon-ok"></span> Enable
Still in the users view every table row has the id of the user:
<tr id="<?php echo $user->id ?>">
In my Usermodel model I have:
public function activateUser($user_id) {
$query = $this->db->get_where('users', ['id' => $user_id]);
return $query->row();
}
In my User controller I have:
public function activate($user_id) {
$this->load->model('Usermodel');
$user = $this->Usermodel->activateUser($user_id);
if ($user->active == 0) {
echo 'activate user';
} else {
echo 'user already active';
}
}
The url users/activate/1 returns "user already active" , while users/activate/2 returns "activate user", as expected. Being new to Codeigniter, I have tried numerous versions of the code above that resulted in errors:
public function activateUser($user_id) {
$query = $this->db->get_where('users', ['id' => $user_id])->update('users', $data);
return $query->row();
}
is one of those versions resulting in errors.
Can you please tell me what shall I change in the code to make work as desired?
If I understand correctly, activateUser should update the database row for that user and then return all updated user information. You are trying to mash two queries together that should be separate. Just take it in two steps:
public function activateUser($user_id) {
$user = null;
$updateQuery = $this->db->where('id', $user_id)->update('users', ['active' => 1]);
if ($updateQuery !== false) {
$userQuery = $this->db->get_where('users', ['id' => $user_id]);
$user = $userQuery->row();
}
return $user;
}
I put in a little bit of error checking; if for instance the user id was not valid this will return null.
Based on that error checking, your controller code might look something like:
public function activate($user_id) {
$this->load->model('Usermodel');
$user = $this->Usermodel->activateUser($user_id);
// $user->active will always be 1 here, unless there was an error
if (is_null($user) {
echo 'error activating user - check user id';
} else {
// I was assuming you would want to do something with the user object,
// but if not, you can simply return a success message.
echo 'user is now active';
}
}

Yii: Getting the role of logged in users and showing content according to role

I want to get the roles of the registered users and show the content to the registered users according to their roles.
I have two users right now.
admin
user(authenticated)
The thing i am trying to do is that when the admin logs in via "webapp/user/login" a sidebarwidget which i have already made should be shown upon login and when the user(authenticated) gets logged in, the user(authenticated) should only be able to see the index.php page.
I am using Yii users and rights. I have looked around and found this piece of code which is for getting the role of the logged in user but I dont know where to place this piece of code to get the output.
Below are two pieces of codes, please do tell me which one will be more useful.
if($user = Users::model()->findAll()) {
foreach($user as $id => $user) {
if(!$user->checkAccess('Authenticated')) {
unset($user[$id]);
}
}
$users = array_values($user); // to reset indices (optional)
}
and this is another piece of code which i have found.
$command = Yii::app()->db->createCommand("SELECT * FROM `authassignment` WHERE userid={$user->id}");
$results = $command->queryAll();
$roles = array();
foreach ($results as $result)
{
$roles[] = $result['itemname'];
}
$this->setState('roles', $roles);
From what I have done following tutorials, here is a proposal.
The authentication can take place in file protected/components/UserIdentity.php :
public function authenticate($native=false){
$record=User::model()->findByAttributes(array('username'=>$this->username));
//can provide function "same" if needed - found it here:
//http://codereview.stackexchange.com/questions/13512
if($record!==null&&$this->same($record->password,crypt($this->password,$record->password)){
$authRoleName=Role::model()->findByAttributes(array('id'=>$record->role_id))->name;
$this->setState('role_name', $authRoleName);
$this->errorCode = self::ERROR_NONE;
}else{
$this->errorCode=self::ERROR_UNKNOWN_IDENTITY;
}
return !$this->errorCode;
}
In this case the several roles (admin, mobile, user, etc) are stored in db (table roles) and each user model has a role_id.
I assume the SiteController does the login (file protected/controllers/SiteController.php):
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login()){
$this->redirect(Yii::app()->user->returnUrl);
}
}
// display the login form
$this->render('login',array('model'=>$model));
}
File protected/models/LoginForm.php:
class LoginForm extends CFormModel
public $username;
public $password;
public $rememberMe;
private $_identity;
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','False username or password.');
}
}
public function login()
{
if($this->_identity===null)
{
$this->_identity=new UserIdentity($this->username,$this->password);
$this->_identity->authenticate();
}
if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
{
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->user->login($this->_identity, duration);
return true;
}
else
return false;
}
In view you could do a role based decision making, like the example below in file protected/views/site/index.php :
<?php
$userModel =User::model()->findByAttributes(array('id'=>Yii::app()->user->getId()));
if($userModel){
if(Yii::app()->user->getState('role_name') == 'admin'){
$this->renderPartial(
//...
);
}else{
//...
}
}
Moreover, if RBAC is on your mind, and you manage to have a proper protected/data/auth.php (there are ways for this, I use command "./protected/yiic rbac" after creating file protected/commands/RbacCommand.php - I can post this latter file if needed) then in any place in your code you simply:
if(Yii::app()->user->checkAccess('admin')){
//staff for admins
}
Also, in this case, you could set the rights of whole actions in controller's function accessRules() by issuing roles instead of usernames:
public function accessRules()
{
return array{
array('allow',
'actions'=>array('index', 'index2', 'view','create','update','getRecordDetails', 'getTotalCount'),
'roles'=>array('admin'),
),
);
}

display logged in user details from in codeigniter

view controller
<?php
class Site extends CI_Controller {
function homePage() {
$this->load->view('homePage');
}
function getValues($username) {
$this->load->model('customer_model');
$data['results']=$this->customer_model->getOne($username);
$this->load->view('view_db',$data);
}
}
I wanna display the logged in user details from database to a page. where the user logs in and it directs to home page and in that , there is link which directs to view the users details according to my design..
view Controller of login
<?php
class Login extends CI_Controller {
function index() {
//loads the main page to be displaye din the page
$this->load->view('login_form');
}
function validate_credentials() {
$this->load->model('customer_model');
$query = $this->customer_model->validate();
if ($query) {//if the user credidential is validated
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
//retrieving the session data
$this->session->set_userdata($data);
redirect('site/homePage');
} else {
$this->index();
}
}
the model view--- i have mentioned only getting a specific user
function getOne($username){
$query=$this->db->query('SELECT * FROM customer WHERE username = $username');
//$this->db->select('*');
//$query= $this->db->get('customer');
return $query->result();
}
and the view.. where now i just wanna retrieve the value and check later i can improve the interface ;)
<?php
//print_r($results);
foreach($results as $row) {
echo $row->id;
echo $row->last_name;
echo "<br/>";
}
?>
i know it should be done through a session .. but how to do it?
Ok so when this person who is now logged in clicks on the link that brings them to the getValues() method. You can just do a check to see if they are logged in, then if they are retrieve their information based on the sessions username key.
function getValues(){
if ($this->session->userdata('is_logged_in')) {
$username = $this->session->userdata('username');
//Get your db results
$this->load->model('customer_model');
$data['results']=$this->customer_model->getOne($username);
$this->load->view('view_db',$data);
} else{
//What you want to happen when they are not logged in.
}
Does that make sense?

CakePHP: sending latest user id to admin's create_employee view

I am trying to send the latest user's id from UsersController to AdminController whose add_employee() action creates a new employee. My users and employees table are separate and what I want to do is when Admin creates a new user its entry go into users table. Then he opens create employee form and the latest user id will be assigned to the new employee the admin is creating. So when admin will open create new employee form the latest user id will be shown in the form.
My UsersController has this code for sending latest user it to AdminsController:
public function get_latest_user_id()
{
$content = $this->User->query("SELECT id FROM users ORDER BY id DESC LIMIT 0,1");
$this->set('latest_user', $content);
}
AdminsController page's add_employee contains this code:
public function add_employee()
{
$this->loadModel('Employee');
$this->set('latest_user', $this->requestAction('/Users/get_latest_user_id'));
if ($this->request->is('post'))
{
$this->Employee->create();
if ($this->Employee->save($this->request->data))
{
$this->Session->setFlash(__('The employee profile has been saved.'));
return $this->redirect(array('action' => 'list_of_employees'));
}
else
{
$this->Session->setFlash(__('The employee profile could not be saved. Please, try again.'));
}
}
}
So UserController's get_latest_user_id function sends latest user id to add_employee function of AdminController. There latest_user is set to latest user id so that when add_employee view is called it is there. But it is not showing. So I want to know that am i doing it right? Please help and thanks.
In add_employee.ctp I am displaying it like this:
echo $latest_user['User']['id'];
Move get_latest_user_id to the User model
public function get_latest_user_id()
{
$user = $this->query("SELECT id FROM users ORDER BY id DESC LIMIT 1");
if (empty($user)) {
return 0;
}
// return only the Id
return $user[0]['users']['id'];
}
In the controller:
public function add_employee()
{
$this->loadModel('Employee');
$this->loadModel('User');
$this->set('latest_user', $this->User->get_latest_user_id());
if ($this->request->is('post'))
{
// ....
}
}
cornelb is right that you should move the method to your User model. Although a more Cake-ish approach would be to use a find('first'), rather than doing a direct query():
// app/Model/User.php
public function getLatest() {
// Get the latest user
$user = $this->find('first', array(
'fields' => array('id'), // Only interested in id? Use this.
'order' => array('User.id' => 'DESC')
));
if (!empty($user)) {
return $user['User']['id'];
} else {
// Nothing was returned, this is very awkward
throw new NotFoundException(__('No users found!'));
}
}
And in your controller:
// app/Controller/AdminsController.php
public function add_employee() {
$this->loadModel('User');
$this->set('latestUser', $this->User->getLatest());
// ...
}

CakePHP check or add user id to posts

I have the following two actions in my controller:
function add()
{
if (!empty($this->data))
{
if ($this->Favour->save($this->data))
{
$this->Session->setFlash('Your favour has been saved.');
$this->redirect(array('controller'=>'favours','action'=>'index'));
}
}
}
function edit($id = null)
{
$this->Favour->id = $id;
if (empty($this->data))
{
$this->data = $this->Favour->read();
}
else
{
if ($this->Favour->save($this->data))
{
$this->Session->setFlash('Your favour has been updated.');
$this->redirect(array('controller'=>'favours','action'=>'index'));
}
}
}
1) I want to be able to add the logged in user id to the add action so that the new post is created with that user as its author id (their is a foreign key in the db table). I'm not sure how to talk to fields within the controller itself.
2) And for the edit action I want to make it so that only the author can edit the post so for example user 200 creates post 20 but user 100 cannot edit this post because his id is not 200! I'm not using ACL for my app but just simple authentication.
I've thought about doing a simple if statement in the action like:
function edit($id = null)
{
$this->Favour->id = $id;
$this->Favour->user_id = $user_id;
if($this->Auth->user('id') != $user_id)
{
$this->Session->setFlash('You do not have permission to edit that favour!');
$this->redirect(array('controller'=>'favours','action'=>'index'));
}
else
{
if (empty($this->data))
{
$this->data = $this->Favour->read();
}
else
{
if ($this->Favour->save($this->data))
{
$this->Session->setFlash('Your favour has been updated.');
$this->redirect(array('controller'=>'favours','action'=>'index'));
}
}
}
Would this be correct? BUT how do I get the user id from the favour?
function add() {
if (!empty($this->data)) {
$this->data['Favour']['user_id'] = $this->Auth->user('id');
if ($this->Favour->save($this->data)) {
//etc
This code assumes:
Your user is logged in
the user can access the add function
You are storing the id value of the logged in user in the field id
You have a foreign key in Favours table called user_id that matches the data type of the user id
As for edit; couple ways of achieving it.
I'd do:
function edit($id) {
$this->Favour->id = $id;
$favour_author = $this->Favour->field('user_id');
// get the user of this post
if($this->Auth->user('id') != $favour_author) {
$this->Session->setFlash('You do not own this post.');
$this->redirect('/someplace');
}
if (empty($this->data)) {
$this->data = $this->Favour->read();
}
// carry on.
If you use Auth Component, you can access the logged-in user record in $this->Auth->user() in controller. So to access the id: $this->Auth->user('id'). If you write your own authentication, it's up to you.
how to talk to fields within the controller itself.
What do you mean?

Categories