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';
}
}
Related
On a blog I'm coding the admin can give an 'author'-permission to users.
When the update of the db table has been successful and their permission has been set to 'author' the admin will be headed back to the list of all current authors.
I want a message("Author has been added." for e.g) to appear on this site when it has been successful.
Of course the possibility of the db-update not working is minimal I think, but I want this case to be considered.
To do this I wanted to set a $newAuthor true when the database has been updated, but it didn't worked trying it with an if.
Here are the functions in the AdminController and the UserRepository with the db query:
//AdminController
public function permissionAuthor()
{
$id = $_GET['id'];
$permission = "author";
$newAuthor = false;
if($this->userRepository->changePermission($id, $permission)) {
$newAuthor = true;
}
header("Location: authors");
}
//UserRepository
public function changePermission($id, $permission)
{
$table = $this->getTableName();
$stmt = $this->pdo->prepare(
"UPDATE `{$table}` SET `permission` = :permission WHERE `id` = :id");
$changedPermission = $stmt->execute([
'id' => $id,
'permission' => $permission
]);
return $changedPermission;
}
// authors.php / the view
<?php if(isset($newAuthor) && $newAuthor == true):?>
<p class="error">Author has been added.</p>
<?php endif;?>
How can I achieve that $newAuthor will only be set to true when the function that updates the database has been successful and the message to be displayed in the view?
EDIT
I tried it with returning $changedPermission in the UserRepository. It might be wrong because it hasn't changed anything.
You can either check the permission before changing it and see if there's a difference, or just check if the UPDATE request worked successfully.
Since the prototype: public PDOStatement::execute ([ array $input_parameters ] ) : bool
You can check if the request has been successful by verifying the return value of the execute function like that:
$result = $stmt->execute([
'id' => $id,
'permission' => $permission
]);
if ($result == FALSE)
echo 'ERROR';
else
echo 'ok';
Also directly put $newAuthor = $this->userRepository->changePermission($id, $permission); in permissionAuthor function.
But one more thing, I don't see where you are calling your permissionAuthor function in your code ? Are you sure it's executed ?
I use this code in my controller LOGIN and they are role type in my database: $users->isAdmin() $users->isOwner() $users->isMember()
public function dologin(Request $request){
$users = new Users;
$email = $request->input('u_email');
$password = $users->setPasswordAttribute($request->input('pwd1'));
//get user id from email
$user_id = $users->get_user_from_email($email);
foreach($user_id as $u){
$u_type = $u->u_type;
}
// Check validation
if (auth()->attempt(['u_email' => $email, 'password' => $password] )){
if($users->isAdmin() == $u_type){
return redirect('admin');
}
if($users->isOwner() == $u_type){
}
if($users->isMember() == $u_type){
}
}else{
}
}
Code in Users Model
public function isAdmin(){
return 0 ;
}
public function isOwner(){
return 1 ;
}
public function isMember(){
return 2;
}
My question:
-how to store role in session for logged in dashboard?
-how to declare in controller this role
Thanks you for all help
Note: the role type are integer 0, 1 and 2. I don't use enum type in my database for this role but integer
To use session in pages, make sure at the start of the page you have session_start(); (before any HTML tag).
After that, when he is logging in and everything is allright set $_SESSION["u_type"]=$u_type; and you can refer to it until you destroy your session.
To check in dashboard if he is admin, owner or member just check
//don't forget session_start(); at the begging of your file
if($_SESSION["u_type"]==0)
//admin
else if($_SESSION["u_type"]==1)
//owner
else if($_SESSION["u_type"]==2)
//member
I need to check if a user is existing in the mgrUser table. now the propblem is the controller is in the adminController while the model is in the mgrUserModel. how do i use Auth for this? Thats the reason why I made a generic login code.
public function login() {
// if ($this->Auth->login()) {
// return $this->redirect($this->Auth->redirectUrl());
// }
// $this->Flash->error(
// __('Username ou password incorrect')
// );
//since the model is in a different view, I needed to includ the mgrModel and create a generic login
//will revamp the code to fit the built in Aut code for php cake
if(isset($_POST['submit'])) {
$User_ID = htmlspecialchars($_POST['user_id']);
$Pass = htmlspecialchars($_POST['pass']);
try {
$mgrUserModel = new MgrUser();
$isValid = $mgrUserModel->find('first', array(
'conditions' => array("user_id" => $User_ID)
));
if($isValid != null){
if (($isValid['MgrUser']['pass']) == $Pass) {
//this doesnot work
$this->Auth->allow();
$this->redirect($this->Auth->redirectUrl());
}
else{
}
}
} catch (Exception $e) {
//echo "not logged in";
}
// this echo will show the id and pass that was taken based on the user_id and pass that the user will input
//for testing only
// echo $isValid2['MgrUser']['id'];
// echo $isValid2['MgrUser']['pass'];
}
}
You need double == to compare things,
function checkMe()
{
if($user == 'me'){
$this->Auth->allow('detail');
}
}
what you did was assign "me" string to variable $user which always returns true because assignment was possible
Anyway you should use it in beforeFilter which is running before every action from this controller, which makes much more sense
public function beforeFilter() {
parent::beforeFilter();
if($user == 'me'){
$this->Auth->allow('detail');
}
}
the Auth component could be configured to read the user information via another userModel (The model name of the users table). It defaults to Users.
please consult the book for appropriate cakephp version: https://book.cakephp.org/3.0/en/controllers/components/authentication.html#configuring-authentication-handlers
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.