How to pass data from model to controller (CodeIgniter, session help) - php

First sorry for my english( it is not my main language ).
I am new in CodeIgniter3 and i like it.
Lets say this is my model:
function login($uname, $upassword)
{
$this->db->where('uname', $uname);
$this->db->where('upassword', $upassword);
$query = $this->db->get('zamestnanci');
foreach ($query->result() as $row) {
$data['zamestnanec'] = $row->tpred_zamestnanci." ".$row->meno_zamestnanci. " ".$row->priezvisko_zamestnanci." ".$row->tza_zamestnanci;;
}
return ($data);
}
And this is my controller:
//Funkcia na prihlásenie používatela
function loginUser()
{
//Načítať model
$this->load->model('user_model');
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$meno = $this->user_model->login($uname, $upassword);
//Ak sa meno a heslo zhoduje
if ($this->user_model->login($uname, $upassword))
{
$this->session->set_userdata('user', $meno);
$data['user'] = $this->session->userdata('user');
redirect('/otk/', $data);
}
else
{
redirect('/user/');
}
}
I want to ask you how to pass/display data from model to session. To $this->session->userdata('user').
Can you explain me the correct process off passing data from model to controller and from model to session. (like if you were trying to explain to a man who is thinking slowly).
I do not want links to documentation, just one or few persons who can explain it on example.

you can pass information from model to controller in two ways.
By using session
first fetch information using query and return that array to controller.
it is good if you return data to controller first then in controller
set up the session by using that returned array.
As in this example.
Model
function login($uname, $upassword)
{
$this->db->select("*");
$tthis->db->from("table_name")
$this->db->where('uname', $uname);
$this->db->where('upassword', $upassword);
$query = $this->db->get('zamestnanci');
// you can user result_array() to get all information in array form.
$this->result = $query->result_array();
return $this->result;
}
In Controller
//Funkcia na prihlásenie používatela
function loginUser()
{
//Načítať model
$this->load->model('user_model');
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$meno = $this->user_model->login($uname, $upassword);
//Ak sa meno a heslo zhoduje
if ($this->user_model->login($uname, $upassword))
{
$this->session->set_userdata('user', $meno); // here you are setting up the session.
$data['user'] = $this->session->userdata('user');
redirect('/otk/', $data);
}
else
{
redirect('/user/');
}
}

Hope this will help you :
get all the user information (in array) from the model whatever you want :
In controller :
First way :
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$lname = $this->input->post('lname');//example
$session_arr['uname'] = $uname;
$session_arr['fullname'] = $fname.' '.$lname; // example
$this->session->set_userdata($session_arr);
Second way :
$user = $this->user_model->login($uname, $upassword);
if ($user != false)
{
// Valid user
// $validate containing user details too. to check add this next line
// print_r($validate);die;
$this->session->set_userdata($user);
redirect('/otk/');
}
for more : https://codeigniter.com/user_guide/libraries/sessions.html#initializing-a-session
$user = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($user);

Just pass the model to controller whether data is correct or not. no need a big loop there in the model
In Model
function login($uname, $upassword)
{
$this->db->where('uname', $uname);
$this->db->where('upassword', $upassword);
$query = $this->db->get('zamestnanci');
$result = $query->result_array();
$count = count($result); # get how many data passed
if ($count == 1) {
return $result;
}
else
{
return false;
}
}
In Controller
function loginUser()
$this->load->model('user_model');
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
//$meno = $this->user_model->login($uname, $upassword);
//Ak sa meno a heslo zhoduje
$validate = $this->user_model->login($uname, $upassword);
if ($validate != false)
{
# Valid user
# $validate conating user details too. to check add this next line print_r($validate);die;
$this->session->set_userdata('user', $uname);
redirect('/otk/');
}
else
{
# Invalid User
redirect('/user/');
}
}
And in otk function just call session value user

Related

Codeingniter3 echo a single element of an associative array

Let's assume I have this controller function
public function index(){
$this->load->model('model_users');
$clienteemail = $this->session->userdata('email');
$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);
$data['title']='La Giumenta Bardata Dashboard'; //array per titolo e dati passati
$this->load->view('auth/template/auth_header', $data);
$this->load->view('auth/template/auth_nav', $cliente);
$this->load->view('auth/clienti/auth_sidebar');
$this->load->view('auth/clienti/client_dash');
$this->load->view('auth/template/auth_footer');
}
model_users is a model that query the db with this function:
public function lettura_dati($clienteemail)
{
$this->db->where('email', $clienteemail);
$query = $this->db->get('user');
if ($query) {
$row = $query->row();
$cliente['nome'] = $row->nome;
return $cliente;
} else {
echo "errore nella ricerca del nome";
}
What I'm trying to do is to use an user email from the session data to retrieve info from the db table.
so I start to retrieve just the name of the user.
The function works, but when in the view I use echo $nome;
I have an error about the conversion between array and string... that's normal, I know, but if I do
print_r($nome);
my output is: Array[0] => 'Pippo'
I just want to output the content of the array.
How can I achieve this?
It looks like you've made a bit of a typo..
Your model:
$row = $query->row(); // Fetch the entireuser
$cliente['nome'] = $row->nome; // Set the name to a value. $cliente isn't defined yet..
return $cliente; // Return the entire $cliente array.
Your Controller:
You are using the above model method and assuming it is returning just the name. It is actually returning the full user.
$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);
Change your model code to the following and it should work as expected.
public function lettura_dati($clienteemail)
{
$this->db->where('email', $clienteemail);
$query = $this->db->get('user');
if ($query && $query->num_rows() > 0) { // Ensure we have got at least 1 row
$row = $query->row();
return $row->nome;
} else {
echo "errore nella ricerca del nome";
}
}
return $row->nome;
instead of:
$cliente['nome'] = $row->nome;
return $cliente;
OR
$cliente_data = $this->model_users->lettura_dati($clienteemail);
$cliente['nome'] = $cliente_data['nome'];
instead of:
$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);

Result returns 0 on password hash validation

I'm in the process of learning how to use the CI framework and am currently working on a user login form. Haven't created a user registration yet, so I'm manually adding credentials into the database. Since I'm testing everything locally, I decided to give crypt a try with no salt which is probably not the best method. I'm using form validation and a callback to check the form data against the information in the database.
here is a snippet from the users controller:
function password_check($password) {
$username = $this->input->post('username', TRUE);
$password = Modules::run('security/create_hash', $password);
$this->load->model('mdl_users');
$result = $this->mdl_users->password_check($username, $password);
if ($result == FALSE) {
//$this->form_validation->set_message('password_check', 'Please login using the correct credentials!');
//return FALSE;
echo $password;
echo '<br/><br/>';
echo $result;
echo '<br/><br/>';
}
else {
return TRUE;
}
}
I echoed the password and the result for testing and password is showing as hashed.
Here is the password_check method:
function password_check($username, $password) {
$table = $this->get_table();
$this->db->where('username', $username);
$this->db->where('password', $password);
$query=$this->db->get($table);
$num_rows = $query->num_rows();
return $num_rows;
if ($num_rows>0) {
return TRUE;
} else {
return FALSE;
}
}
I'm sure the reason this isn't working is because the password in the DB is being treated as a literal string and not as hashed, but I'm not sure as to how I can compare it as a hash.
You could do something like this: get the user from the model and then check the saved value from the password with the hashed value from the user. If you would use md5 it would look a bit like this.
controller
$this->load->model('user_model');
public function login() {
$name = $this->input->post('name');
$password = $this->input->post('password');
$user = $this->user_model->get_user_through_name($name);
if($user['password'] == md5($password)) {
//logged in
} else {
//wrong password
}
}
model
public function get_user_through_name($name) {
$query = $this->db->get_where('Users', array(
'username' => $name
));
return $query->row_array();
}

How to put $_GET value in a variable in codeigniter

I am having trouble retrieving and putting the user id in the url into a variable. Here is my controller that I am trying to do this with. I have read the documentation in the user guide,however I am not getting any results.
here is my url structure:
clci.dev/account/profile/220
Controller:
public function profile()
{
$this->load->helper('date');
$this->load->library('session');
$session_id = $this->session->userdata('id');
$this->load->model('account_model');
$user = $this->account_model->user();
$data['user'] = $user;
$data['session_id'] = $session_id;
//TRYING TO MAKE A VARIABLE WITHT THE $_GET VALUE
$user_get = $this->input->get($user['id']);
echo $user_get;
if($user['id'] == $session_id)
{
$data['profile_icon'] = 'edit';
}
else
{
$data['profile_icon'] = 'profile';
}
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/profile_template', $data);
}
Am I flat out doing this wrong, or are there adjustments that I need to make in my config files?
thanks in advance
In codeigniter, instead of having something.com/user.php?id=2 we use something.com/user/2 and the way to get that 2 is using this:
$this->uri->segment(3)
for more info http://ellislab.com/codeigniter/user-guide/libraries/uri.html
edit:
based on your url: clci.dev/account/profile/220 you would need $this->uri->segment(4)
You would set up your controller function as follows
public function profile($id = false)
{
// example: clci.dev/account/profile/222
// $id is now 222
}
I suppose at this point that the value for $_GET['id'] is intended to be 220 so here:
To get 220, you would have to do it this way (except the get value in question is other than 220 as shown in your url above)
Let's say you visit: clci.dev/account/profile/220. Follow the comments for more info.
public function profile()
{
$this->load->helper('url'); //Include this line
$this->load->helper('date');
$this->load->library('session');
$session_id = $this->session->userdata('id'); //Ensure that this session is valid
$this->load->model('account_model');
$user = $this->account_model->user(); //(suggestion) you want to pass the id here to filter your record
$data['user'] = $user;
$data['session_id'] = $session_id;
//TRYING TO MAKE A VARIABLE WITHT THE $_GET VALUE
$user_get = $this->uri->segment(3); //Modify this line
echo $user_get; //This should echo 220
if($user_get == $session_id) //Modify this line also
{
$data['profile_icon'] = 'edit';
}
else
{
$data['profile_icon'] = 'profile';
}
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/profile_template', $data);
}
I hope that helps your gets your started in the right track.
you can directly get like this:
public function profile($user_id = 0)
{
//So as per your url... $user_id is 220
}

Controller help and functions

I have a general create function that submits a new user to the database - this works fine. Where I am is stuck is the following.
I know that I need the user that is signing up to have clicked the link in the email before the account can login. How do I implement that into my if statement when I run the create function?
I am a bit confused as to how to set my errors if any thing is correct or wrong to do with the activation process I have currently set the messages using $this->form_validation->set_message();. Do I need to use set_flashdata();? and how will echo these into the view?
When I create a new user I have the userActive field set at 0 by default and also the default group is set to users
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
public function index()
{
$data['companyName'] = $this->core_model->companyDetails()->coreCompanyName;
$data['pageTitle'] = "Create User";
$this->load->view('frontend/assets/header', $data);
$this->load->view('frontend/users', $data);
$this->load->view('frontend/assets/footer');
}
public function create(){
//If form validation fails load previous page with errors else do the job and insert data into db
if($this->form_validation->run('createUser') == FALSE)
{
$data['success'] = "";
}else{
$username = $this->input->post('userName');
$password = $this->input->post('userPassword');
$firstname = $this->input->post('userFirstName');
$lastname = $this->input->post('userLastName');
$email = $this->input->post('userEmail');
$passwordHash = $this->encrypt->sha1($password); // Lets encrypt the password why sha1? MD5 is for tossers
$activateCode = $this->_activateCode(10);
// If the data is correct follow through with db insert
if($this->users_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$activateCode))
{
$data['success'] = TRUE;
redirect('frontend/users/create','refresh');
}
}
$data['companyName'] = $this->core_model->companyDetails()->coreCompanyName;
$data['pageTitle'] = "Create User";
$this->load->view('frontend/assets/header', $data);
$this->load->view('frontend/user_create', $data);
$this->load->view('admin/assets/footer');
echo get_class($this);
var_dump(method_exists($this, '_activateCode'));
}
function _userRegEmail($activateCode,$email,$firstname,$lastname){
$data['companyName'] = $this->core_model->companyDetails()->coreCompanyName;
$data['companyEmail'] = $this->core_model->companyDetails()->coreCompanyEmail;
$data['companyContact'] = $this->core_model->companyDetails()->coreContactName;
$data['firstName'] = $firstName;
$data['lastName'] = $lastname;
$data['email'] = $email;
$data['activateCode'] = $activateCode;
$this->email->from($this->core_model->companyDetails()->coreCompanyEmail, $this->core_model->companyDetails()->coreCompanyName);
$this->email->to($email);
$this->email->subject($this->core_model->companyDetails()->coreCompanyName, 'User Registration Confirmation');
$messageContent= $this->load->view('email_templates/userReg','', TRUE);
$this->email->message($messageContent);
//$this->email->send();
}
function usersconfirm(){
$activateCode = $this->uri->segment(3);
if($activateCode == '')
{
$this->form_validation->set_message('userConfirmError', 'Sorry you did not have a correct Activation Code.');
}
$userConfirmed = $this->users_model->confirm_user($activateCode);
if($userConfirmed){
$this->form_validation->set_message('userConfirmed', 'Thanks your account is now active you may login!');
}else{
$this->form_validation->set_message('userRecord', 'I am sorry we do not have any details with that Activation Code');
}
}
function _username_check($username)
{
if($this->users_model->username_taken($username))
{
$this->form_validation->set_message('username_check', 'Sorry the username %s is taken!');
return FALSE;
}else{
return TRUE;
}
}
function _email_check($email)
{
if($this->users_model->email_check($email))
{
$this->form_validation->set_message('email_check','Sorry there is already a user with this %s');
return FALSE;
}else{
return TRUE;
}
}
function _activateCode($length)
{
return random_string('alnum', $length);
}
}
/* End of file users.php */
/* Location: ./application/controllers/users.php */
You can determine if the user has clicked the activation link by checking the database for userActive in your if statement.
You can use flash data, sure. You can retrieve flash data with:
$this->session->flashdata('item'); to echo out to the view.
See http://codeigniter.com/user_guide/libraries/sessions.html > flash data

Codeigniter return username based on id

I created a helper for returning a user's username if the user's unique id is known.
if ( ! function_exists('get_username'))
{
function get_username($user_id)
{
$ci=& get_instance();
$ci->load->database();
if (empty($user_id))
{
return FALSE;
}
$ci->db->select('username');
$ci->db->where('id', $user_id);
$ci->db->where('activated', 1);
$ci->db->where('banned', 0);
$ci->db->limit(1);
$query = $ci->db->get('users');
if ($query->num_rows() > 0) //if user exists
{
$row = $query->row();
return $row->username;
}
else
{
return FALSE;
}
}
}
This works in my view if for instance I try:
echo get_username($this->uri->segment(3)); //uri segment 3 is a user id.
However want to send the username to my view via controller. I tried the following in my controller:
function write_message($user_id = '') //function parameter is 3rd uri segment
{
$data['username'] = get_username($user_id);
$this->load->view('my_view', $data);
}
Then in my view I have
echo $username which echoes array instead of the username. What am I doing wrong here?
Your criteria should be clear, and the usrname should be unique i think, so...
if ($query->num_rows() == 1) //if user exists, and unique
{
$res = $query->result_array();
return $res[0]['username'];
}
else
{
return FALSE;
}
Upon using <pre>print_r($username)</pre> in my view (as suggested by Alfonso) it was easy to spot the issue, being an identical variable name in my view which was another array. Correct answer goes to anyone that gives a good suggestion/input for my helper or Alfonso if he submits his post as answer.

Categories