store post value in session variable - codeigniter

i post value through ajax in codeigniter controller function , and trying to store value in session like this
function abc{
$studio = $_POST['studio'];
$trnr_type = $_POST['trnrtyp'];
$this->session->set_userdata('studio',$studio),$this->session->set_userdata('trnr_type',$trnr_type)
}
and use this value
$st = $this->session->userdata('studio');
$tr = $this->session->userdata('trnr_type');
but not getting value in session variable.

Load the session library in your controller by the following
$this->load->library('session');
then you have to post the data to the codeigniter controller
then at the controller you have to do the following
$sess_array = array(
'studio' => $this->input->post('studio'),
'trnr_type' => $this->input->post('trnrtyp'),
);
$this->session->set_userdata('studio',$sess_array);

//set user data
$this->session->set_userdata('username',$username);
//get user data
if($this->session->has_userdata('username'))
{
$userid = $this->session->userdata('username');
}
Hope this is what u are looking for

Before call abc function load sesion library
function abc() {
$session = array('studio'=>$_POST['studio'],'trnr_type'=>$_POST['trnrtyp']);
$this->session->set_userdata($session);
}

1. Load session library into your controller:
$this->load->library('session');
2. Get your data:
$studio = $this->input->post('studio');
$trnrtyp = $this->input->post('trnrtyp');
3. Set session data:
$this->session->set_userdata('studio', $studio);
$this->session->set_userdata('trnrtyp ', $trnrtyp );
4. Get session data:
$st = $this->session->userdata('studio');
$tr = $this->session->userdata('trnr_type');

This is what the user guide says to do
http://www.codeigniter.com/user_guide/libraries/sessions.html#adding-session-data
public function abc() {
$sessiondata = array(
'studio' => $this->input->post('studio'),
'trnrtyp' => $this->input->post('trnrtyp')
);
$this->session->set_userdata($sessiondata);
}
Make sure you have set your session save path on config.php don't leave it null

Related

Stuck at Error = Method Illuminate\Database\Eloquent\Collection::save does not exist

Trying to save data while open page but stuck at error :
"Method Illuminate\Database\Eloquent\Collection::save does not exist."
I have 2 database :
Buffalodata
Buffalomilkrecord
From 2nd table i need to get the avg of totalmilk and update the same to main database (1). This help me to show updated avgmilk data on dashboard front page.
Route:
Route:: get('buffalo-details', 'App\Http\Controllers\BuffalodataController#buffalodetails');
BuffalodataController Controller :
public function buffalodetails()
{
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')->pluck('buffaloID')->toArray();
foreach ($buffalidforavgmilk as $id )
{
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->sum('totalmilk');
$avgbuffalocount = Buffalomilkrecord::where('buffaloID',$id)->count();
$getavg = $milkperid / $avgbuffalocount;
$data = Buffalodata::find($buffalidforavgmilk);
$data->avgmilk = ($getavg);
$data->save ();
// dump([$milkperid,$avgbuffalocount,$getavg,$data,$id]);
}
return view ('pages.Buffalo.BuffaloDetails',[---------]);
}
Thanks again in Advance
When you pass an Array to ::find(), it returns a Collection, which doesn't have a save() method. This is your code:
// This is an Array of `buffaloID` values
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')->pluck('buffaloID')->toArray();
...
// `$data` is now a `Collection` of `Buffalodata` instances
$data = Buffalodata::find($buffalidforavgmilk);
// This now fails, as `Collection` doesn't have a `save()` method
$data->save();
You can rewrite your code as follows:
Buffalodata::whereIn('buffaloID', $buffalidforavgmilk)->update(['avgmilk' => $getavg]);
This will update all records in a single call. If you want to iterate, that's an option too:
$data = Buffalodata::find($buffalidforavgmilk);
foreach ($data as $record) {
$record->avgmilk = $getavg;
$record->save();
}
Or, since you have $id already:
$record = Buffalodata::find($id);
$record->avgmilk = $getavg;
$record->save();

codeigniter 3 issue with fetch session ID

i want check session and get current user details only one row i new here plz help
public function profile() {
$this->load->view('header');
$this->load->model('brid_groom_fetch');
$this->session->userdata('uname');
//This below line fetch model db data
$row = $this->brid_groom_fetch->get_program_specific_gender();
//here i have check data is in session..
$session_id = $this->session->userdata(
array('uname' => $row->uname));
print_r($sesid);
}
Why don't you use basic == operator ?
public function __construct() {
parent::__construct();
$this->load->model('brid_groom_fetch');
// you need to load session library
// Have you loaded ?
$this->load->library('session');
}
public function profile() {
$this->load->view('header');
// you do not need to load in all method.
// we have already loaded in __construct()
// $this->load->model('brid_groom_fetch');
// use variable
$uname = $this->session->userdata('uname');
//fetch data from db
$row = $this->brid_groom_fetch->get_program_specific_gender();
if ($row->uname == $uname) {
$session_id = $this->session->userdata('session_id');
var_dump($session_id);
}
}
You are setting userdata with
$this->session->set_userdata(array('uname' => $yourname));
or
$this->session->set_userdata('uname',$yourname);
To check what value is set in the userdata you need to use
$sess_name = $this->session->userdata('uname');
print_r($sess_name);
And then validate this $sess_name you have received.
You can also unset the userdata by using
$this->session->unset_userdata('uname');

CodeIgniter Unset A Signle Session Item In An Multidimensional Array

On my User.php library in my login function I create admin sessions by
$create_session = array(
'is_logged' => true,
'user_id' => $row->user_id
);
$this->CI->session->set_userdata('admin', $create_session);
The issue is when I try to unset admin session data individually it does not unset the session I select.
Var Dump:
Array
(
[__ci_last_regenerate] => 1449906266
[admin] => Array
(
[is_logged] => 1
[user_id] => 1
)
)
Logout function on library:
Does not Unset: Preferred Way
public function logout() {
$user_data = $this->CI->session->userdata('admin');
unset($user_data['is_logged']);
unset($user_data['user_id']);
}
But when I use this way below it works
public function logout() {
$this->CI->session->unset_userdata('admin');
}
For some reason will not let me unset session data individually from an array in sessions.
Question How am I able to unset codeigniter session data individually that are in my admin session array?
Full User.php library
<?php
class User {
private $user_id;
private $username;
public function __construct() {
$this->CI =& get_instance();
$this->CI->load->library('session');
}
public function login() {
if ($this->validate_password() == true) {
$this->CI->db->select('*');
$this->CI->db->from($this->CI->db->dbprefix . 'user');
$this->CI->db->where('username', $this->CI->input->post('username'));
$query = $this->CI->db->get();
if ($query->num_rows() > 0) {
$row = $query->row();
$create_session = array(
'is_logged' => true,
'user_id' => $row->user_id
);
$this->CI->session->set_userdata('admin', $create_session);
$this->user_id = $row->user_id;
$this->user_group_id = $row->user_group_id;
$this->username = $row->username;
return true;
} else {
return false;
}
}
}
public function is_logged() {
$get_session = $this->CI->session->userdata('admin');
return $get_session['is_logged'];
}
public function logout() {
$user_data = $this->CI->session->userdata('admin');
unset($user_data['is_logged']);
unset($user_data['user_id']);
}
public function validate_password() {
if (password_verify($this->CI->input->post('password'), $this->stored_hash())) {
return true;
} else {
return false;
}
}
public function stored_hash() {
$this->CI->db->where('username', $this->CI->input->post('username'));
$query = $this->CI->db->get($this->CI->db->dbprefix . 'user');
if ($query->num_rows() > 0) {
$row = $query->row();
return $row->password;
} else {
return FALSE;
}
}
}
Note:
I have two lots of sessions one admin for back end and catalog for front end that's why in array.
Using unset() by itself will not remove the values from the CodeIgniter session. You would need to save those changes to the session using $this->CI->session->userdata('admin', $user_data) again.
For example:
<?php
$user_data = $this->CI->session->userdata('admin');
print_r($user_data);
// Shows: Array ( [is_logged] => 1 [user_id] => 123 )
unset($user_data['is_logged']);
unset($user_data['user_id']);
print_r($user_data);
// Shows: Array ( )
// Check what values are saved in the session:
print_r($this->CI->session->userdata('admin'));
// Shows: Array ( [is_logged] => 1 [user_id] => 123 )
// Save your changes to the session
$this->CI->session->set_userdata('admin', $user_data);
// Check what values are saved in the session (now that we've updated the session)
print_r($this->CI->session->userdata('admin'));
// Shows: Array ( )
So, you need to do the following steps to update arrays stored in your session:
Get values from session: $arr = userdata('userdata')
Remove value(s) from array: unset($arr['key'])
Save changes to session: set_userdata('userdata', $arr)
As a workaround, you may be able to edit the $_SESSION directly, bypassing the CodeIgniter's Session library:
unset($_SESSION['admin']['is_logged']);
unset($_SESSION['admin']['user_id']);
I wouldn't advise bypassing the Session library like this, but it might suit your purposes more than the steps I've listed above.
Thanks to #Kirk Beard for advice I have found way to use CodeIgniter session and unset individually data that is in side my admin array();
I create the admin multidimensional array session
$create_session = array(
'is_logged' => true,
'other_item' => 'something'
);
$this->session->set_userdata('admin', $create_session);
Then if you need to unset a single item in the admin array.
unset($this->session->userdata['admin']['is_logged']);
Works for me.
To get multidimensional array session.
echo $this->session->userdata['admin']['is_logged'];
Or
$userdata = $this->session->userdata('admin');
echo $userdata['user_id'];
Generate sessions as $this->CI->session->set_userdata($create_session); instead of $this->CI->session->set_userdata('admin',$create_session);
such as
$create_session = array(
'is_logged' => true,
'user_id' => $row->user_id
);
$this->CI->session->set_userdata($create_session);
Now unset by name even individually
$this->CI->session->unset_userdata('is_logged');
$this->CI->session->unset_userdata('user_id');

How to delete session in cakephp 3.0?

all code is in one controller
My code goes like this.
public function login()
{
$session = $this->request->session();
$session_event_id = $session->read('Events.event_id');
$session_division_id = $session->read('Events.division_id');
if(!$session_event_id || !$session_division_id) {
$event_table = TableRegistry::get('Events');
$event = $event_table->find('all', ['fields' => ['id'], 'order' => 'id desc'])->first();
$session->write('Events.event_id', $event->id);
$session_event_id = $session->read('Events.event_id');
$division_table = TableRegistry::get('Divisions');
$division = $division_table->find('all',['fields' => ['id'], 'conditions' => ['event_id' => $event->id]])->first();
$session->write('Events.division_id', $division->id);
$session_division_id = $session->read('Events.division_id');
}
}
By above code i am able to write and read session values but while logout i want to delete those session data
public function logout()
{
$session = $this->request->session();
$this->$session->delete();
return $this->redirect($this->Auth->logout());
}
Warning (4096): Object of class Cake\Network\Session could not be
converted to string [APP/Controller/UsersController.php, line 56]
Notice (8): Object of class Cake\Network\Session to string conversion
[APP/Controller/UsersController.php, line 56]
Error: Call to a member function delete() on a non-object File
/var/www/html/MEX/src/Controller/UsersController.php
You're looking for $this->request->session()->destroy();
http://book.cakephp.org/3.0/en/development/sessions.html#destroying-the-session
Just a tip - there's not much of a point for storing a variable $session for a function that small, where the reuse of $session isn't necessary. The only case I'd store $this->request->session(); in a variable is when I'm accessing the session for multiple read and writes all in the same function.
(As far as the error is concerned, #Eagle is correct in that you're referencing '$this' twice by the use of that stored variable.)
Thank You for your supports and help finally i found solution of my problem by myself
$session = $this->request->session();
$session->delete('Events.event_id');
$session->delete('Events.division_id');
by doing so, i am able to clear session data. Thank you

codeigniter validate

Hello I have a forum and when a user creates a comment, I want that if he didn't type anything I want to show him an error that he must type something in :) but I dont know how to put him the the thread he is in.
I have this
if($this->_submit_validate_comment() == false) {
$this->post(); return;
}
function _submit_validate_comment() {
$this->form_validation->set_rules('kommentar', 'kommentar', 'required|min_length[4]');
return $this->form_validation->run();
}
You could do this with jquery but if that is not an option you could get the forum or topic id from the url (assuming your are using the url this way).
For example:
http://yoursite.com/forum/topic/12
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
redirect('/forum/topic/'. $topic_id);
}
Or
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
$this->topic($topic_id);
}
Hope this helps.
Thanks for helping i can see what you mean but it just dont work :b,
i have this
$topic_id = $this->uri->segment(3);
$this->post($topic_id);
return;
and my url is
localhost:8888/ci/index.php/forum/create_comment
it looks like it cant find the ID
my URL to the forum is
localhost:8888/ci/index.php/forum/post/33
this is my functions
function create_comment() {
if($this->_submit_validate_comment()
== false) { $id = $this->uri->segment(3);
$this->post($id); return;
//echo "validate fejl, kontakt lige
en admin!"; } else { $data =
array( 'fk_forum_traad' =>
$this->input->post('id'),
'brugernavn' =>
$this->session->userdata('username'),
'indhold' =>
$this->input->post('kommentar'),
'dato' => 'fejl' );
$this->load->model('forum_model');
$this->forum_model->create_comment($data);
redirect('/forum/post/'.
$this->input->post('id').'',
'refresh'); }
}
function post($id) {
$this->load->model('forum_model');
$data['query'] =
$this->forum_model->posts($this->uri->segment(3));
$this->load->model('forum_model');
$data['comments'] =
$this->forum_model->comments($this->uri->segment(3));
$data['content'] = 'forum_post_view';
$this->load->view('includes/template',
$data); }
Why not pass in the return uri in the form submission using a hidden input field? No additional work will be needed by the controller other than validation of the return uri before performing a redirect.
Place the validation error string in session class's flashdata for echoing out in the form, along with any other data used to pre-populate your form)

Resources