Codeigniter-login with session - codeigniter

i am trying to do a login with sessions but it doesn't seem to be working because when i log in the session data on the view is not being displayed. once logged in it should read something like: 'Welcome Jon' but it doesn't. What could be the issue
controller fn
function login_user()
{
if(isset($_POST['login']))
{
$data = $this->Model_students->fetchUserData();
if(!empty($data))
{
var_dump($data);
foreach ($data as $key => $value) :
$user_id = $value->id;
$firstname = $value->firstname;
$lastname = $value->lastname;
$grade = $value->grade;
$email = $value->email;
$images = json_decode($value->userfile);
endforeach;
$user_info = array(
'id' => $user_id,
'firstname' => $firstname,
'lastname' => $lastname,
'grade' => $grade,
'email' => $email,
'images' => $images[0]->file_name,
'is_logged_in' => TRUE
);
$this->session->set_userdata($user_info);
redirect('Students/homepage');
}
else
{
$this->session->set_flashdata('error', 'Error! Invalid username or password');
redirect('Students/login_user');
}
}
else
{
$this->load->view('signup');
}
}
model
the join here is for a different table in the same db where the common row is id..not sure if the join is correct too
public function fetchUserData()
{
$this->db->select('users.*, user_images.*');
$this->db->from('users');
$this->db->join('user_images', 'users.id=user_images.user', 'inner');
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get();
if($query->num_rows() == 1 ) :
foreach($query->result() as $row):
$data[] = $row;
endforeach;
return $data;
endif;
}
view the img scr here should display the user image based on what is saved on the db when he/she first registered
</head>
<body>
<h3>Welcome <?php $this->session->userdata('$firstname')?>.</h3>;
<img class ="img-circle" src="<?=base_url();?>uploads/users/<?=$this->session->userdata('userfile/file_name');?>" width="250" height="auto">

There's a typo in your views. where the session variable should be without the $ symbol.
<h3>Welcome <?php echo $this->session->userdata('firstname'); ?>.</h3>;
Also, check if the $user_info contains the expected data. Do a var_dump($user_info) and see just before creating the session.

there could be many issues with it.
1: your are passing a variable in the string which is not valid ( $this->session->userdata('$firstname') ) remove the $ from the first name;
2: there has to be a constructor in the controller so that the session could be called when ever the object is created;
hope it will solve your problem

Related

Display name instead of id in url laravel

I would just like to ask how do I display the name of the business instead of it's id.
It's currently displayed like this, localhost:8000/1/Belen'sChoice and desired output is
localhost:8000/Belen'sChoice. I can get the name however it says 'trying to find id'.
Controller
public function show($id)
{
$categories = Category::all();
$businesses = Business::find($id);
if (Auth::check()) {
$userId = Auth::user()->id;
$users = User::where('id', $userId)->get();
$posts = Post::where('business_id', $businesses->id)->get()->sortByDesc('created_at');
$supporters = Supporter::where('user_id', $userId)->get();
$photos = Image::where('business_id', $businesses->id)->get();
$albums = Album::where('business_id', $businesses->id)->get();
$count = 0;
if ($businesses->user_id != Auth::user()->id) {
$businesses->views = $businesses->views + 1;
$businesses->save();
} else {
$businesses->views = $businesses->views;
}
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
'users' => $users,
'posts' => $posts,
'supporters' => $supporters,
'count' => $count,
'images' => $photos,
'albums' => $albums,
]);
} else {
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
]);
}
}
Blade
<a class="text-center" href='{{ url("/businessprofile/".$business->id."/".str_replace(" ", "" ,$business->name)) }}'><img class="bprof-img" src='{{ asset("storage/$business->logo") }}'>{{ $business->name }}</a>
Web.php
Route::get('/businessprofile/{id?}/{name}', 'BusinessController#show');
TIA
take one Column in your business migration
$table->string('slug')->unique();
and save it like this way in your controller
//use this at the bottom of your controller
use Illuminate\Support\Str;
$business = new Business;
$business->slug = Str::slug($request->name) // whatever you request dring //creating a business row
//and after that save it
$business->save();
then in your controller find the row using slug
public function show($slug)
{
$business = Business::where('slug',$slug)->first();
//and rest of your operation
}
href='{{ url("/".str_replace(" ", "" ,$business->slug))}}'
then in your web
Route::get('/{slug}', 'BusinessController#show');

Codeigniter User's Data

Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = 'Login';
$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 {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$this->db->select("*");
$this->db->from("user");
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->result();
}
else {
return false;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}

Codeigniter Join Not Displaying Group By Correct

I have this model function below which lets me join both tables. Printed results are at bottom of question.
<?php
class Forum_model extends CI_Model {
public function get_forums() {
$this->db->select('f.*, fc.*');
$this->db->from('forum_category fc', 'left');
$this->db->join('forum f', 'f.forum_id = fc.category_forum_id', 'left');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
}
How ever when I go to look at in on my view it displays it like image below
The two General categories news, lounge should be displayed on the one panel. For some reason it displays the two general categories in own panel.
Question: How is it possiable to display the two categories together? I have tried $this->db->group_by('fc.category_forum_id')
Image
Controller
<?php
class Home extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('reports/thread_analytics_model');
$this->load->model('forum/forum_model');
}
public function index() {
$results = $this->forum_model->get_forums();
echo "<pre>";
print_r($results);
echo "</pre>";
$data['forums'] = array();
foreach ($results as $result) {
$data['forums'][] = array(
'forum_name' => $result['forum_name'],
'category_name' => $result['category_name']
);
}
$data['content'] = 'common/home_view';
$this->load->view('theme/default/template_view', $data);
}
}
View
<?php foreach ($forums as $forum) {?>
<div class="panel panel-home">
<div class="panel-heading"><h1 class="panel-title"><?php echo $forum['forum_name'];?></h1></div>
<div class="panel-body">
<table class="table">
<tbody>
<tr>
<td><?php echo $forum['category_name'];?></td>
</tr>
</tbody>
</table>
</div>
</div><!-- Panel -->
<?php }?>
Printed Results Image
A possible solution with your approach would be:
class Forum_model extends CI_Model {
public function get_forums() {
$arrGroupedData = array();
$this->db->select('f.*, fc.*');
$this->db->from('forum_category fc');
$this->db->join('forum f', 'f.forum_id = fc.category_forum_id', 'left');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach($query->result_array() AS $arrCategory)
{
$arrGroupedData[$arrCategory['forum_id']][] = $arrCategory;
}
return $arrGroupedData;
} else {
return false;
}
}
}
But in my opinion - you should probably split up your queries
1 query to get the forums and 1 query to get all categories from your forums
and stick it together in a tree structure
example for you
$forums = array();
$results = array(
array(
'forum_name' => 'general',
'category_name' => 'news1'
),
array(
'forum_name' => 'general',
'category_name' => 'news2'
),
array(
'forum_name' => 'latter',
'category_name' => 'news3'
),
);
foreach ($results as $result)
{
if(in_array($result['forum_name'],$forums))
{
$array = array($result['category_name']);
array_push($forums[$result['forum_name']],$array);
}
else
{
$forums[$result['forum_name']][] = array(
'forum_name' => $result['forum_name'],
'category_name' => $result['category_name']
);
}
}
echo '<pre>';
print_r($forums);

how to get data from database throught model using codeigniter with for each loop

http error occured while calling data from model using function
model
public function getProductCombo() {
$q = $this->db->get_where('products', array('type' => 'combo'));
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
controller
function sets() {
$this->sma->checkPermissions();
$this->load->helper('security');
$this->data['error'] = (validation_errors() ? validation_errors() :
$this->session->flashdata('error'));
// problem in this line also
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
$bc = array(array('link' => base_url(),
'page' => lang('home')),
array('link' => site_url('sales'),
'page' => lang('products')),
array('link' => '#', 'page' => "sets")
);
$meta = array('page_title' => "Add Sets", 'bc' => $bc);
$this->page_construct('sales/sets', $meta, $this->data);
}
First of all, No need to include the curly braces for $q->result
foreach ($q->result as $row)
{
$data[] = $row;
}
No need to use validation_errors in your php file.You can directly load your form page.Use validation_errors() in view page.
In your Controller, do this
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
Then in your formpage you can echo
<?php echo validation_errors(); ?>
change this line to
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
this
$this->data['showcombo'] = $this->load->sales_model->getProductCombo();
Because your
model name is
public function getProductCombo()
{
}
Firstly you load model in controller. And then called function, which you have defined in model..
$this->load->model('sales_model','sales'); // sales is alias name of model name
$this->data['showcombo'] = $this->sales->getComboProduct();

Codeigniter dropdown only retrieve last data from db

I use CI form with form_dropdown helper and tried to pull Mysql data into its options, from the below code, its only retrieve the last record from db into the option list?
please advise what is wrong with my code?
Model
public function getStates() {
$query = $this->db->get('states');
$return = array();
if($query->num_rows() > 0){
$return[''] = 'please select';
foreach($query->result_array() as $row){
$return[$row['state_id']] = $row['state_name'];
}
}
return $return;
}
Controller
$this->load->model('db_model');
$data['options'] = $this->db_model->getStates();
$this->load->view('create_new', $data);
View
$state = array(
'name' => 'state',
'id' => 'state',
//'value' => set_value('state', $state)
);
<?php echo form_label('State', $state['id']); ?>
<?php echo form_dropdown($state['name'], $options); ?>
<?php echo form_error($state['name']); ?>
<?php echo isset($errors[$state['name']])?$errors[$state['name']]:''; ?>
send full query result from the model to the view like this
Model
public function getStates() {
$query = $this->db->get('states');
return $query->result();
}
let the controller as it is and now you can populate states in dropdown like this:
View
<?php
foreach($options as $opt){
$options[$opt->state_id]=$opt->state_name;
}
echo form_dropdown($state['name'], $options);
?>
Try this:
function getStates() {
$return = array();
$query = $this->db->get('states')->result_array();
if( is_array( $query ) && count( $query ) > 0 ){
$return[''] = 'please select';
foreach($query as $row){
$return[$row['state_id']] = $row['state_name'];
}
}
return $return;
}

Resources