One user having multiple card ( php, mysql ) - php

I have a question, I am trying to create a way in which the user who is logged in can register multiple cards under his name. I understand the concept but just cannot apply it. So need help.
So basically I have 2 tables one for users and another for the cards, which are as shown.
new_users
user_money
So basically i created all this table and most of the information are inserted directly by me for example the orig_id.
So basically what I just want to do is that the user logged in can create multiple cards. Maybe the new_users.id could be equal to user_money.orig_id , but I am not sure how can I make them equal to each other and when a new user registers and enters more cards how can that user id and orig id equal to each other.
This is my controller for login and the controller when user adds a card.
public function login(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|max_length[32]');
if ($this->form_validation->run() == FALSE){
$this->load->view('header_view');
$this->load->view('body_view');
$this->load->view('footer_view');
}else{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->load->model('main_page');
$user_id = $this->main_page->login_user($email, $password);
if($user_id){
$user_data = array(
'user_id' => $user_id,
'email' => $email,
'loggedin' => true
);
$this->session->set_flashdata('loggedin_success','you are loggedin');
redirect('main/Admin');
}else{
redirect('main/login');
}
}
}
And this is the function for the new card getting registered.
public function insertUserCard(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('cardname', 'CardName', 'required');
$this->form_validation->set_rules('iban', 'IBAN', 'required');
$this->form_validation->set_rules('cc', 'CC', 'required|max_length[4]');
$this->form_validation->set_rules('amount', 'Amount', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('header_view');
$this->load->view('admin_view');
$this->load->view('footer_view');
}else{
$data = array(
'card_type' => $this->input->post('cardname'),
'iban' => $this->input->post('iban'),
'cc' => $this->input->post('cc'),
'amount' => $this->input->post('amount'),
'orig_id' => 52
/*so the orig id here is randomly added by me */
);
$this->load->model('main_page');
$this->main_page->storeCardInfo($data);
redirect('main/Admin');
}
}
And just incase if needed the models for both the table data being inserted.
public function login_user($email , $password){
$this->db->where('email', $email);
$this->db->where('password', $password);
$result = $this->db->get('new_users');
if($result ->num_rows() == 1){
return $result->row(0)->id;
}else{
return false;
}
}
public function storeCardInfo($data){
$insert = $this->db->insert('user_money',$data);
return $insert;
}
So would like if someone could help me on how to get one user have multiple rows in the user_money table.
I am using codeigniter and mysql

Just use the user_id that is stored into $user_data inside of login().
First, to make user_data a session variable so that the whole controller can access it, change the line in login() which declares $user_data as a local variable to assign it to a session variable.
Change:
$user_id = $this->main_page->login_user($email, $password);
if($user_id){
$user_data = array(
...
To:
$user_id = $this->main_page->login_user($email, $password);
if($user_id){
$this->session->set_userdata(array(
...
Then... you can change the line in insertUserCard():
'orig_id' => 52
/*so the orig id here is randomly added by me */
to just use the session:
'orig_id' => $this->session->userdata('user_id');
I think, since you are "new to all this", you should perhaps ensure your MySQL database is setup properly with a Foreign Key Constraint. (and that you understand how that works)

Related

How can I display the name of my admin full name after login - Codeigniter

I am having a trouble on displaying my admin's full name, like for example admin full name is John Doe, it is not displaying. I am still learning codeigniter please give me advice thank you!
here is my controller
//Get username
$username = $this->input->post('username');
//Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->role_model->login($username, $password);
if ($user_id) {
// Create session
$user_data = array(
'user_id' => $user_id,
'name' => $user_id->name,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//Set message
$this->session->set_flashdata('user_loggedin','You are now logged in');
redirect('pages/index');
here is my View - where I would like to display my full name, as you can see 'name' is the data field I have to display but it is does not show anything, it gives an error that says name is not defined.
<li><a> Welcome, <?php echo $this->session->name ?> </a></li>
Model
public function login($username, $password){
//Validate
$this->db->where('username',$username);
$this->db->where('password',$password);
$result = $this->db->get('users');
if ($result->num_rows() == 1) {
return $result->row(0)->id;
}else{
return false;
}
}
Your method login() returns only id = digit (return $result->row(0)->id;), not object (in controller your get $user_id->name).
Do this, in the model:
if ($result->num_rows() == 1) {
return $result->row(0); // fix
}else{
return false;
}
In the controller:
$user = $this->role_model->login($username, $password);
$user_data = array(
'user_id' => $user->id, // fix
'name' => $user->name, // fix
'username' => $username,
'logged_in' => true
);
It shows undefined because it is indeed undefined.
In your view your're trying to echo the returning value of a function called userdata(), does that function actually exist? Or is $this->session->userdata an array? in which that case, you need to use [ index ] to acces a member within an array. i.e. $this->session->userdata['name'], but also, that member needs to exist first.
controller :
if($this->Login_model->login_valid($email,$password))
{
$sessiondata = array(
'username' => $email
);
$this->session->set_userdata('logged_in', $sessiondata);
redirect('narson');
}
else
{
$this->session->set_flashdata('error',"Invalid Username And password");
redirect('login');
}
model:
public function login_valid($username,$password)
{
$this->db->where('username',$username);
$this->db->where('password',$password);
$query = $this->db->get('admin');
if($query->num_rows() > 0)
{
return true;
}
else
{
return false;
}
}

How to access $_$ESSION data stored in array code igniter

I have been following a tutorial on youtube about CodeIgniter. The tutorial only relies on $username $_SESSION variable and doesn't touch on other aspects of $_SESSIONs. According to code igniter documentation regarding $_SESSION you can simply call the session super global with the key. This is where my problem starts.
VAR_DUMP($_SESSION)
a var_dump of $_Session provides the following info (I have truncated other fields to keep it shorter)
array (size=5)
'__ci_last_regenerate' => int 1526800056
'' => null
'userID' =>
array (size=1)
0 =>
array (size=14)
'userID' => string '1' (length=1)
'firstname' => string 'Tim' (length=3)
'lastname' => string 'Coetzee' (length=7)
'pword' => string 'xyz' (length=4)
'email' => string 'someone#gmail.com' (length=17)
What I want to do
I simply want to be able to call a $_SESSION super global as such $_SESSION['email'] or $_SESSION['userID'] The way I want to access the session vars is EXACTLY as you should do it according to docs, thus I believe my
problem is in my controller() or the way im setting the session data() as can be viewed below
Problem
Lets say I want to display the userID from above var_dump() info in the view just as a test I do the following... echo $_SESSION['userID'];
The above leads to error
Message: Object of class stdClass could not be converted to string
Okay sure enough however what is the object name I should call to get say firstname ?
I tried this as per official docs
echo $this->session->firstname AND echo $this->user_data('userID');
which resulted in same error.
I realize the $_SESSION data seems to be saved in a multi-dimensional array so I tried a foreach() as such
foreach ($_SESSION as $sessions)
{
foreach ($sessions as $value)
{
echo $value;
}
}
which gives me the error:
Message: Invalid argument supplied for foreach()
However after two more similar errors by the last iteration it returns the values of all the sessions, so Im guessing im doing something wrong in the loop.
Code Follows Below
Users_model.php
public function login($username, $password)
{
// Validate
$this->db->where('username', $username);
$this->db->where('pword', $password);
$stmnt = $this->db->get('users');
if($stmnt->num_rows() == 1){
return $stmnt->row(1);
} else {
return false;
}
}
Controller.php
public function login(){
$data['title'] = 'Sign In';
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// Get username
echo $username = $this->input->post('username');
// Get and encrypt the password
echo $password = $this->input->post('password');
// Login user
$user_id = $this->users_model->login($username, $password);
if($user_id){
// Create session
$user_data = array(
'username' => $username,
'userID' => $user_id,
'logged_in' => true
);
$username = user_data ['username'];
$userID = user_data ['userID'];
$logged_in = user_data ['logged_in'];
$this->session->set_userdata($username );
$this->session->set_userdata($userID );
$this->session->set_userdata($logged_in);
// Set message
//$this->session->set_flashdata('user_loggedin', 'You are now logged in');
redirect('pages/index');
} else {
// Set message
// $this->session->set_flashdata('login_failed', 'Login is invalid');
redirect('users/failed');
}
}
}
$config.php
$autoload['libraries'] = array('form_validation','session', 'pagination');
Any help advice, or constuctive criticism appreciated
Hope this will help you :
if you don't want to change your model query set session like this
$user = $this->users_model->login($username, $password);
if($user)
{
$user_data = array(
'username' => $username,
'userID' => $user->id,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//$this->session->set_flashdata('user_loggedin', 'You are now logged in');
redirect('pages/index');
}
else
{
// Set message
// $this->session->set_flashdata('login_failed', 'Login is invalid');
redirect('users/failed');
}
print individual session key like this :
echo $this->session->userdata('username');
echo $this->session->userdata('userID');
echo $this->session->userdata('logged_in');
and whole session like this :
print_r($this->session->userdata());
Note : for CI Version 3.1.8, access like this :
$username = $this->session->username;
$userid = $this->session->userID;
for more https://www.codeigniter.com/user_guide/libraries/sessions.html#retrieving-session-data
When you echo $_SESSION['userID']; you are trying to display whole array like string, it is immposible.
Also you cannot use two foreach loops because in the first cycle of outer loop there is integer ('__ci_last_regenerate' => int 1526800056) as argument of inner loop, so you get error.
Following your session array structure you can call to fields like that:
echo $_SESSION['userID'][0]['firstname'];
or better:
$name = $this->session->userdata('firstname');

Should I compare $get value to stored relavent db value?

I am trying to implement resetting a users password in codeigniter.
I've created a form that the users sends their email and it creates a row in a 'reset' table that stores their token that is created as well as attaches the token the link sent to the email.
The final step is actually resetting the password. I am not understanding how to make the correct comparison when checking the token attached to the email against the one stored in the db associated with that email, or if that is even the right way to go about it.
In the current code I have, I am unable to get it to pass validation and actually reset the password. Here is my code:
This is the model for creating the token and sending the email:
public function validate_retrieve($data) {
$query = $this->db->where($data)->get('users', '1');
foreach ($query->result() as $user)
{
$user->email;
$user->salt;
$user->id;
}
$token = sha1($user->email.$user->salt).dechex($user->id);
$reset_token = array(
'token' => $token,
'email' => $user->email
);
$insert = $this->db->insert('reset', $reset_token, '1');
return $reset_token;
}
and the controller:
public function retrieve()
// REQUEST PASSWORD RESET
// LOADED WHEN THE FORM IS SUBMITTED OFF THE PASSWORD PAGE AND SENDS THE EMAIL WITH TOKEN AND INSTRUCTIONS
{
$this->load->library('form_validation');
$this->load->library('session');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->load->model('user_model', 'um');
$this->load->library('encrypt');
$this->load->helper('url');
$submit = $this->input->post('submit');
$salt = $this->_salt();
if($submit)
// IF THE SUBMIT BUTTON IS SET
{
// START PROCESS TO CREATE $USER VARIABLE THAT HOLDS WHAT THE USER ENTERED IN THE FORM AND THAT CAN GET CHECKED AGAINST THE DB IN THE MODEL
$user = $this->um->validate_retrieve(array('email' => $this->input->post('email')));
// IF THE USER IS CREATED AND CHECKS OUT AND ALL OF THE ERRORS ARE CLEARED ON THE FORM
if( $user && $this->form_validation->run() == TRUE ) {
$domain = "clci.dev/index.php";
// CREATE A TOKEN LINK TO SEND TO THE USERS EMAIL THAT EXIST IN THE DB AND WAS ENTERED
$token = $user['token'];
$link = "http://www.".$domain."/auth/reset/?token=$token";
$this->load->library('email');
$this->email->from('noreply#cysticlife.org', 'CysticLife');
$this->email->to($this->input->post('email'));
$this->email->subject('Reset Password');
$this->email->message("Please go to the following web address to reset your password:\n\n$link\n\n-Your friends at CysticLife\n\nPlease remember to add the cysticlife.org domain to your address book to ensure that you receive your CysticLife e-Notifications as requested.");
$this->email->send();
redirect('auth/success');
exit;
}
$this->form_validation->run() == FALSE;
$data['main_content'] = 'auth/password';
$this->load->view('includes/templates/main_page_template', $data);
$data['email_error'] = 'This email is invalid';
}
}
now here is what I'm having trouble with, the model for resetting:
public function verify_token($token)
{
$this->db->where('token', $token);
$query = $this->db->get('reset');
if ($query->num_rows() == 1) {
return TRUE;
} else {
return FALSE;
}
}
public function reset_password()
{
$salt = $this->_salt();
$query = $this->db->get('reset', 1);
$row = $query->row();
$data = array(
'password' => $this->encrypt->sha1($salt . $this->encrypt->sha1($this->input->post('password'))),
'salt' => $salt
);
$this->db->where('email', $row->email);
$this->db->update('users', $data);
}
and the controller:
public function reset_password()
{
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('user_model', 'um');
$this->load->library('encrypt');
$this->load->helper('url');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
$this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|matches[password]');
$salt = $this->_salt();
$submit = $this->input->post('submit');
if($submit)
{
$validToken = $this->um->verify_token($token);
if($this->form_validation->run() == TRUE && $validToken == TRUE)
{
$this->um->reset_password(array('password' => $this->input->post('password', $salt)));
$data['main_content'] = 'auth/success';
$this->load->view('includes/templates/home_page_template', $data);
}
$this->form_validation->run() == FALSE;
$data['main_content'] = 'auth/reset';
$this->load->view('includes/templates/main_page_template', $data);
}
}
I seem to be very close but I am definitely stuck. Any help is greatly appreciated.
http://yoursitename.com/reset/[hashcode]
send the link to the member email, went password have reset by user.
on web site you will retrieve the hashcode to compare with your database
public function reset($hashcode)
{
if($hashcode!=null)
{
// compare with db
// if success
// redirect to create new password page
// or show create new password form
}
}

How do I pull a variable from a model to use on my controller in CodeIgniter?

I am trying to use a variable in my controller that has been created in my model.
Here is the model:
public function validate_retrieve($data) {
$query = $this->db->where($data)->get('users', '1');
foreach ($query->result() as $user)
{
$user->email;
$user->salt;
$user->id;
}
$token = sha1($user->email.$user->salt).dechex($user->id);
$reset_token = array(
'token' => $token,
'email' => $user->email
);
$insert = $this->db->insert('reset', $reset_token, '1');
return $reset_token;
}
and on my controller I'm trying to use $token that was created in the model:
public function retrieve()
// REQUEST PASSWORD RESET
// LOADED WHEN THE FORM IS SUBMITTED OFF THE PASSWORD PAGE AND SENDS THE EMAIL WITH TOKEN AND INSTRUCTIONS
{
$this->load->library('form_validation');
$this->load->library('session');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->load->model('user_model', 'um');
$this->load->library('encrypt');
$this->load->helper('url');
$submit = $this->input->post('submit');
$salt = $this->_salt();
if($submit)
// IF THE SUBMIT BUTTON IS SET
{
// START PROCESS TO CREATE $USER VARIABLE THAT HOLDS WHAT THE USER ENTERED IN THE FORM AND THAT CAN GET CHECKED AGAINST THE DB IN THE MODEL
$user = $this->um->validate_retrieve(array('email' => $this->input->post('email')));
// IF THE USER IS CREATED AND CHECKS OUT AND ALL OF THE ERRORS ARE CLEARED ON THE FORM
if( $user && $this->form_validation->run() == TRUE ) {
$domain = "clci.dev/index.php";
// CREATE A TOKEN LINK TO SEND TO THE USERS EMAIL THAT EXIST IN THE DB AND WAS ENTERED
$token = $this->um->token;
$link = "http://www.".$domain."/auth/reset/?token=$token";
$this->load->library('email');
$this->email->from('noreply#cysticlife.org', 'CysticLife');
$this->email->to($this->input->post('email'));
$this->email->subject('Reset Password');
$this->email->message("Please go to the following web address to reset your password:\n\n$link\n\n-Your friends at CysticLife\n\nPlease remember to add the cysticlife.org domain to your address book to ensure that you receive your CysticLife e-Notifications as requested.");
$this->email->send();
redirect('auth/success');
exit;
}
$this->form_validation->run() == FALSE;
$data['main_content'] = 'auth/password';
$this->load->view('includes/templates/main_page_template', $data);
$data['email_error'] = 'This email is invalid';
}
}
thanks in advance
You're trying to access an array as an object.
$reset_token = $this->um->validate_retrieve($whatever_id);
$token = $reset_token['token'];
That's how you access the token portion of the returned results from this function.
And according to your latest update, you would actually access it like this:
$token = $user['token'];
Because in the following line you assign the results of the validate_retrieve method to the variable $user:
$user = $this->um->validate_retrieve(array('email' => $this->input->post('email')));

Unable to change Identity to 'username' in Codeigniter Ion Auth?

I have installed ion auth and everything is up and functional. The only problem I have is I want to change the login to use the visitors username instead of e-mail. I change the CONFIG option in the ion_auth.php config file and it still doesnt work. Is there an extra step Im missing??
ion_auth config
/**
* A database column which is used to
* login with.
**/
$config['identity'] = 'username';
login() in the controller
//log the user in
function login()
{
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('email', 'E-mail Address', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{ //check to see if the user is logging in
//check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('email'), $this->input->post('password'), $remember))
{ //if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect($this->config->item('base_url'), 'refresh');
}
else
{ //if the login was un-successful
//redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('auth/login', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else
{ //the user is not logging in so display the login page
//set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['email'] = array('name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
$this->load->view('auth/login', $this->data);
}
}
login() model
public function login($identity, $password, $remember=FALSE)
{
if (empty($identity) || empty($password) || !$this->identity_check($identity))
{
return FALSE;
}
$query = $this->db->select($this->identity_column.', id, password, group_id')
->where($this->identity_column, $identity)
->where('active', 1)
->where($this->ion_auth->_extra_where)
->limit(1)
->get($this->tables['users']);
$result = $query->row();
if ($query->num_rows() == 1)
{
$password = $this->hash_password_db($identity, $password);
if ($result->password === $password)
{
$this->update_last_login($result->id);
$group_row = $this->db->select('name')->where('id', $result->group_id)->get($this->tables['groups'])->row();
$session_data = array(
$this->identity_column => $result->{$this->identity_column},
'id' => $result->id, //kept for backwards compatibility
'user_id' => $result->id, //everyone likes to overwrite id so we'll use user_id
'group_id' => $result->group_id,
'group' => $group_row->name
);
$this->session->set_userdata($session_data);
if ($remember && $this->config->item('remember_users', 'ion_auth'))
{
$this->remember_user($result->id);
}
return TRUE;
}
}
return FALSE;
}
Why are you still processing email in the controller (instead of username)?
You need to change your controller since it is still grabbing email from POST and using it to try to login.
You should add an index in the users table of username column

Categories