When updating the user's details, the database will update all the information, although when the page refreshes, the previous information is showing and it does not update unless the user has logged out and logged back in. I am new to CodeIgniter. Could someone please help me or tell me what to do, I would really appreciate it. Thanks in advance.
This is my Model:
function updateAccount($submit_userid, $submit_phone, $submit_address, $submit_eaddress) {
$this->db->where("intMemberID", $submit_userid);
$this->db->update("tblMembers", array(
"strPhoneNumber" => $submit_phone,
"strMemberAddress" => $submit_address,
"strEmailAddress" => $submit_eaddress,
));
}
This is my Controller:
class UpdateController extends CI_Controller {
public function updateAccount() {
$this->load->model('userModel');
$data['userdata'] = $this->session->userdata('userobject');
$submit_userid = $this->input->post('userid');
$submit_phone = $this->input->post('phone');
$submit_address = $this->input->post('address');
$submit_eaddress = $this->input->post('eaddress');
$this->userModel->updateAccount($submit_userid, $submit_phone, $submit_address, $submit_eaddress);
$this->load->view('updateView', $data);
}
}
because you show the old data obtained from the last session. read data directly from database and show it in the view
Your user data is being fetched from the session, rather than the database, you have :
$data['userdata'] = $this->session->userdata('userobject');
This data is put into the session on user login, most likely, thus your problem. You need to change source of the data to
$data['userdata'] = $this->userModel->returnAccount($this->user_id);
or whatever method you have for retrieving the data, to fetch it from your database. Do you have any returnAccount methods in your model? I assume you are not the one who wrote it.
Related
I'm currently developing an MLM Website using Codeigniter Framework.
And I am working on registration now. I can register successful with referral user
The problem is every 3 registration using my referral username/id i need to run another query because in 1st and 2nd referral I earned 200. and in 3rd user will refer i will only earn 100.
How can I do that in Codeigniter? anyone done this? please help
Let me throw some light on this
So lets say you make a post for every registration, the post goes to a class names registration and a register method, and the referral id runs as a session (refID). Also, you have a registration model, this is what you should likely do:
class registration extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('registration_model');
}
//ensue to check for the existence of the refID session before processing
function register(){
if($_POST){
//first run form validation
//you should have auto loaded the form_validation library
//and created a rules function that carries the form rules
$rules = $this->rules();
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == FALSE){
//load view here
}else{
//first, get post data
//then get the number of registration done by user using the refID
//if registration is greater than 2, set earnings to 100
//set earnings to 200
//then proceed to insert registration and do something else
//get post data, assumed post data
$name = $this->input->post('name');
$email = $this->input->post('email');
//get number of registrations
$numOfRegs = $this->registration_model->getRegByRefID();
//set the earnings from the number of registrations
$earning = $numOfRegs < 3 ? 200 : 100;
//please note that the for $numOfRegs = 4, $earnings will be 100, as this was not specified in the question
//at this point, you have set the earnings, you can proceed to do whatever you wish to do, perhaps insert the records
//please note that this code block just explains what you can likely do after setting the earnings
$insert = array(
"name" => $name,
"email" => $email,
"earning" => $earning
);
$this->registration_model->insert($array);
// then do anything else
}
}else{
//load view here
}
}
}
Now this is how your registration model will look like this
class Registration_model extends CI_Model{
function __construct(){
parent::__construct();
}
function getRegByRefID(){
$refID = $this->session->refID;
return $this->db->get_where('mydb', array("refID" => $refID))->num_rows();
}
}
I hope this explains what you really wants, and helps you. If you find any difficulty, kindly comment and lets sort it out.
I've set up a log in process where a verification code is generated, and when successful, is then removed. However, i want to make sure that if there's multiple verification codes for the same user, upon log in success, delete all records for that user.
Here's my code
if ($model->validate() && $model->login()) {
//delete this verification code
$verificationCode->delete();
//delete all existing codes for user_id
VerificationCode::model()->deleteAll('user_id',$user->id);
Yii::app()->user->setReturnUrl(array('/system/admin/'));
$this->redirect(Yii::app()->user->returnUrl);
}
However, this seems to just delete all the records, regardless on different user_id's in table. Can anyone see where I'm going wrong?
If you want to delete record with specified attributes, the cleanest way for this is to use deleteAllByAttributes():
VerificationCode::model()->deleteAllByAttributes(['user_id' => $user->id]);
Seems you call the function delete() in wrong way ... try passing value this way
VerificationCode::model()->deleteAll('user_id = :user_id', array(':user_id' => $user->id));
For Yii2, the documented way is to use the function deleteAll().
I normally pass the arguments as an array, like so:
VerificationCode::deleteAll(['user_id' => $user->id]);
Also, you can use the afterDelete method, to make sure that everytime or everywhere someone deletes one verificationCode, your application will also delete every userVerificationCode. Put this in your verificationCode model class:
protected function afterDelete()
{
parent::afterDelete();
VerificationCode::model()->deleteAll('user_id = :user:id',[':user_id' =>$this->user_id]);
//... any other logic here
}
You can use below method for deleting all user_id entry from database:
$criteria = new CDbCriteria;
// secure way for add a new condition
$criteria->condition = "user_id = :user_id ";
$criteria->params[":user_id"] = $user->id;
// remove user related all entry from database
$model = VerificationCode::model()->deleteAll($criteria);
or you can use another method directly in controller action
VerificationCode::model()->deleteAll("user_id= :user_id", [":user_id"
=>$user->id]);
use below method for redirecting a URL
$this->c()->redirect(Yii::app()->createUrl('/system/admin/'));
I am new to practicing CakePHP, I want to get value from the webuser and my controller will search that value from the DB. I am just wondering how I insert my $_post value add it to following code?
class DataviewsController extends AppController {
public $components = array('RequestHandler');
public function customer($id = null) {
$this->loadModel('Customer','Stock');
if (!$this->Customer->exists($id)) {
throw new NotFoundException(__('Invalid customer'));
}
$options = array('conditions' => array('Customer.' . $this->Customer->primaryKey => $id));
// Send the customer to the view
$this->set('customer', $this->Customer->find('first', $options));
$this->set('_serialize',array('customer'));
}
You can access post data in $this->request->data and get data in $this->request->query. As for your second question, I'm not sure what you are asking when it refers to the code you posted.
yes you can do with cakephp request handler object
here is very good example to create form and taking user data input and search from particular table. from that you can have very good idea how to implement in your application
just go throw this link Or this one for cakephp 2.0 and let me know if you need any more help
I want to have a delete button underneath blogs entered just by the owner of the current profile, I have tried implementing a deleteMyBlog function but no joy so far. whats the best way to go about this?
Here is my view. I know I would need but some delete button here but I'm not sure how to fit around my current foreach loop:
<?foreach($blogs AS $viewData):
$delete = $viewData['id'];
{
$id = $viewData->id;
$title = $viewData->title;
$body = $viewData->body;
$username = $viewData->username;
$date = $viewData->date;
?>
<b> <?=$title?></b>
<p><?=$body?></p>
<p>posted by:<?=$username?></p>
<p>date: <?=$date?></p>
<?=anchor("blog/deleteMyBlog/$delete", 'delete')?>
<hr>
<?
}
?>
My model:
class Blogmodel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
function deleteMyBlog($id)
{
$this->db->where(array('id' => $id));
$this->db->delete('blogs');
}
public function get_last_ten_entries()
{
$query = $this->db->get('blogs', 10);
return $query->result();
}
public function insert_entry()
{
$this->title = $this->input->post('title');
$this->body = $this->input->post('text');
$this->username = $this->session->userdata('username');
$this->date = date("Y-m-d");
$this->db->insert('blogs', $this);
}
}
Controller:
class Blog extends CI_Controller {
public function _construct()
{
parent::__construct();
$this->load->model('Blogmodel','Blog');
$this->load->model("profiles");
}
function deleteMyBlog($id) {
$this->blogs->deleteBlog($id);
redirect('blog');
}
public function index()
{
$username = $this->session->userdata('username');
$viewData['username'] = $username;
$this->load->model('Blogmodel');
if($this->input->post('act') =='create_post')
{
$this->Blogmodel->insert_entry();
}
$viewData['blogs'] = $this->Blogmodel->get_last_ten_entries();
$this->load->view('shared/header');
$this->load->view('blog/blogtitle', $viewData);
$this->load->view('shared/nav');
$this->load->helper('form');// Load the form helper.
// Lets set the stuff that will be getting pushed forward...
$data = array();
$data['form_open']=form_open();
$data['form_title'] = form_input(array('name' => 'title'));
$data['form_text'] = form_textarea(array('name' => 'text'));
$data['form_hidden'] = form_hidden('act','create_post');
$data['form_submit'] = form_submit('submit','Make Post');
$this->load->view('blog/blogview');
$this->load->view('blog/post', $data);
$this->load->view('shared/footer');
}
}
Thanks again guys
Simplest way is with assigning username to a variable, then with the SQL statement.
Delete from tbl where colname='$username'
That's the way I would do it, other people might have different methods. So all respect to those who would use somethin different
You're getting the error because of this bit:
<?foreach($blogs AS $viewData):
$delete = $viewData['id'];
It should be this:
$delete = $viewData->id;
You're using the exact same data a line later correctly, why are you trying to use $viewData which is an object as an array here, but an object 2 lines later. Other than that the rest of what you're doing there should work fine but it is rather dangerous in practice. If I go to your site and type the url to that controller function with a blogId at the end that blog goes away, at no point are you checking that the user actually should be allowed to delete that blog. Obscurity != Security. Meaning that just because you think people won't find the link doesn't mean they won't.
Personally I save the userId of a logged in user to the session and save the session to the database. Then when I do anything to user records I do a check to ensure the user making the change has the authorization to make that change.
So your delete function would be something like this:
function deleteMyBlog($id)
{
$this->db->where('username',$this->session->userdata('username');
$this->db->where('id',$id);
$this->db->delete('blogs');
}
Also you should be using userId's not usernames for saving to other tables, the indexes work better on numerical ID's as far as I know and it's less overall data in the tables. Saving userId 342 to your blogs table takes up less space than saving username bobsyouruncle3421.
For the record, I know this isn't part of the question but actually deleting things from the database has downsides. Not the least of which is screwing up the indexing and slowing down queries in the long run. A far better solution is adding a status or active column to any tables you may want to delete from and giving them a value of 1 for active and 0 for deleted. Then instead of actually deleting the item you change it's active column to 0. When displaying items you add a check for active = 1 to the display query.
This serves two purposes, first you don't mess up the indexing, the record is never removed just modified so the indexes remain intact. Second and nearly important is you never have the possibility of accidentally deleting something you didn't mean to delete, it is never really gone. So you could "undelete" anything at any time.
When my users log into the website their first name, last name and ID are missing from the session data because my session data is coded to take post data and submit into the session table in my database.
Because user logs in with email and password in my session data only email appears and nothing else does.
How can I make first name, last name and id appear in my session table in my db? I want to some how grab these details from the database when user is logging in and provide it in my $u_data array so it get's posted upload login success.
Here is my code:
<?php
class Login_Model extends CI_Model {
public function checkLogin() {
$this->db->where('email', $this->input->post('email')); //compare db email to email entered in form
$this->db->where('password', $this->hashed()); //compare db password to hashed user password
$query = $this->db->get('users'); //get the above info from 'user' table
if ($query->num_rows() == 1) { //if number of rows returned is 1
$u_data = array( //new variable with session data
'user_id' => $this->db->insert_id(),
'email' => $this->input->post('email'),
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'logged_in' => TRUE
);
$this->session->set_userdata($u_data); //send data from variable to db session
return TRUE;
} else {
return FALSE;
}
}
public function hashed() { //hashing method
// sha1 and salt password
$password = $this->encrypt->sha1($this->input->post('password')); //encrypt user password
$salt = $this->config->item('encryption_key'); //grab static salt from config file
$start_hash = sha1($salt . $password);
$end_hash = sha1($password . $salt);
$hashed = sha1($start_hash . $password . $end_hash);
return $hashed;
}
}
If you're tracking sessions in your DB, two solutions come to mind.
First, you could select the first/last from the user table and insert it into the session table. This requires changes to your application.
Second, you could set up a view for your application, in which the session table is automatically joined with the appropriate user, but that assumes you already have some unique identifier for which user it is in the session (was that the email address?*). This solution would not require any changes to the application code, but would require changes to the DB, which may be the preferred method depending upon your deployment requirements (or it may not :) ).
* as a side note, if you're using email addresses for unique identifiers, be aware that some people share email addresses as you decide if this is the right solution for you.
It'd be as simple as doing something like:
session_start();
$_SESSION['userdata'] = $u_data;
within your CheckLogin method. The session is just a regular PHP array that happens to be automatically preserved for you. You can put anything you want into it, but you do have do put things into it yourself - PHP won't do it for you.
comment followup:
gotcha. So, you simply modify you class to fetch that information from the DB once the login's authenticated. I don't know how your DB class works, but instead of merely checking if there's a matching row, fetch the first/last name, using a query something like this:
select firstname, lastname
from users
where email=$email and password=$password
If you get a result row, you know it's a valid login, and then you just retrieve the name data. I have no idea how your db class works, but it shouldn't be too hard to get it to do that.
When I'm working with Auth systems in CodeIgniter I have made it a practice to include the "user" object globally in views, and also globally in my controllers, by fetching the userdata in the constructor, like so...
<?php
class My_Controller extends Controller {
private $the_user; //global var to store current user data
function My_Controller() {
parent::Controller();
$data->the_user = $this->ion_auth->get_user(); //get user data
$this->load->vars($data); //load into all views as $the_user "$the_user"
$this->the_user=$data->the_user; //load into private class variable "$this->the_user"
}
At that point $the_user variable object is available in all views by default AND $this->the_user is always available to controller functions. It always represents the user currently logged in.
I am using Ion_auth for authentication and fetching the user, so that piece you would have to fill in.
I actually just constructed a "How-to" to implement extended Controller classes so all the Auth logic is automatically inherited to all "protected" Controllers.
The following solved this issue for me. I looked at one of my old questions on here and used my common sense.
I made this edit to my code.
if ($query->num_rows() == 1) { //if number of rows returned is 1
$user = $query->result();
$u_data = array( //new variable with session data
'user_id' => $user[0]->id,
'email' => $this->input->post('email'),
'first_name' => $user[0]->first_name,
'last_name' => $user[0]->last_name,
'logged_in' => TRUE
);