I already created as session named "verified" as shown below (in my login controller):
foreach($result as $row)
{
$sess_array = array(
'id' => $row->memberid, //Session field: id.
'username' => $row->member_userunique //Session field: username.
);
// Create a session with a name verified, with the content from the array above.
$this->session->set_userdata('verified', $sess_array);
}
Now, when a user open a page called book (with a controller named book) i want to add one more additional variable called "book_id" to my "verified" session.
This is what i have done
function index()
{
//Add a new varible called book_id
$this->session->set_userdata('book_id', $titleID);
}
When i tried to retrieve the 'book_id' using the following method:
$session_data = $this->session->userdata('verified');
$article_id = $session_data['book_id'];
$user_id = $session_data['id'];
It only able to retrieve the 'id' however the 'book_id' is not defined. But if do a var_dump() on $this->session->all_userdata() i can see that the 'book_id' session variable has been successfully appended.
After reading the CI documentation about session, i realized that the code above will not work as i have not tell it to which session should i add the variable to.
Can anyone point me to the right direction?
You do as follows in your index() method:
$session_data = $this->session->userdata('verified');
$session_data['book_id'] = "something";
$this->session->set_userdata("verified", $session_data);
This way you retrieve the contents of the variable (i.e. the array that you persisted earlier), you add another key to the array (book_id), and then store it again. Now you will be able to do, as I assume you want to:
$sess = $this->session->userdata("verified");
echo $sess['book_id'];
Related
I am trying to reset/clear a specific session value in codeigniter right before the page redirect happens but it still keeps the value in session and doesn't clear it. If I comment the code that redirects the page, then it clears the session value. Below is the code I am using :
$this->session->set_userdata('my_session_variable', '');
$this->session->unset_userdata('my_session_variable');
redirect($my_url);
Any idea how to fix this?
Set Session Userdata
$data = array(
'name' => 'username',
'user_id' => 'someid',
'logged_in' => TRUE,
);
$this->session->set_userdata($data);
Unset Userdata
$data = array('name', 'user_id', 'logged_in');
$this->session->unset_userdata($data);
redirect($my_url);
$this->session->unset_userdata('my_session_variable');
...should work. Just for debug and see what is going on, you can do:
$this->session->unset_userdata('my_session_variable');
var_dump($_SESSION);
die;
...and see what happens. If it works as expected, remove the die; add the same var_dump() at the very begining of the redirected page.
Remember that you can always do:
unset($_SESSION['my_session_variable']);
...to remove session data. More info here.
My problem: I can't access session data in the view, which I tried to save in the controller before rendering the view.
In my opinion there's an error when storing the session data. (It's necessary for me to modify the session data after creating it, not only in the single action.)
ProcessController.php
public function actionNew() {
$formhash = md5(time());
$hashList = array();
$hashList[$formhash]['processingNumber'] = '';
//fill with empty model
$hashList[$formhash]['model'] = $this->loadModel();
//store hashList in session
Yii::app()->session['hashList'] = $hashList;
$this->render('/process', array('hashValue => $formHash));
}
Now in the view I need the data from the session to show them to the user. But when dumping the hashList it just dumps "null" (Maybe because the saving in the controller didn't went well).
process.php
<?php
$form = this->beginWidget('CActiveForm', array(
'id' => 'process_form',
//several other things...
));
//Output: null
CVarDumper::dump(Yii::app()->session['hashList'],10,true);
?>
I tried to use $_SESSION instead of Yii::app()->session, which gives me access to the data in the view. But when handling other actions in the Controller the $_SESSION variable is undefined.
Any suggestions?
Thank you.
Long answer is:
Regarding to this documents:
$session=new CHttpSession;
$session->open();
$value1=$session['name1']; // get session variable 'name1'
$value2=$session['name2']; // get session variable 'name2'
foreach($session as $name=>$value) // traverse all session variables
$session['name3']=$value3; // set session variable 'name3'
You can use as well:
Yii::app()->session->set('hashList', $hashList);
Yii::app()->session->get('hashList');
And set it again.
Beside this session thing, why do not you use this:
$this->render('/process', array('hashValue => $formHash, 'hashList' => $hashList));
So you do not need to save it in a session if you can reach it directly into the view.
According to the documentation your code should work. An alternative might be to use the following, but it does the same:
Yii::app()->session->add('hashList', $hashList); // set the value
$hashList = Yii::app()->session->get('hashList'); // get the value
I expect the problem either a debugging problem, meaning you have observed cached or otherwise outdated data or a problem in parts of your code that you have not shown.
Understanding about Question:
When any user logged into website , there is one page shows records
coming from mysql database table. What I want is to show records
randomly when user first time shows that page. Then after the
records must have same sequence of display as user shows first time
when logged into account.
The sequence of records remain persist until logout.
But the sequence will again change randomly when user logged in
again.
Create cache with results when user first login and then just read from cache, not from DB.
For cache you can use function serialize and save data to file (unique name for each user). Then just unserialize form file.
Example:
Lanch login() to simulate user login to site, and then replace it with notLogin() to simulate user already login on site. Notice that users points change when user is login, but not when he is already on site.
//when user is login
function login(){
//1. here you log in user;
$userID = '345353';
//2. And you get some data drom DB
$randomRowsFromDb = getRandomDataFromDB();
//3. Save it to cache
saveToCache($userID, $randomRowsFromDb);
//4. Display it (optional)
display($randomRowsFromDb);
}
//when user is already on site
function notLogin(){
$userID = '345353';
$data = loadFromCache($userID);//load from cache
display($data);//display cached data instead of taking it from DB
}
//function geting random data form DB
function getRandomDataFromDB(){
return
array(
array('id'=>'43534','login' => 'John', 'points' => rand(0,100)),
array('id'=>'27725','login' => 'Anna', 'points' => rand(0,100)),
array('id'=>'23664','login' => 'Jerremy', 'points' => rand(0,100)),
array('id'=>'87855','login' => 'Kate', 'points' => rand(0,100)));
}
function display($dataToDisplay){
var_dump($dataToDisplay);
}
function saveToCache($userID, $data){
file_put_contents($userID.'.cache', serialize($data));
}
function loadFromCache($userID){
if (file_exists($userID.'.cache')){
$file = file_get_contents($userID.'.cache');
return unserialize($file);
}else{
//in case cache is missing
$data = getRandomDataFromDB();
saveToCache($userID, $data);
return $data;
}
}
I get one good solution:
>> After login use rand function.
>> When you fetch the records, stores them in SESSION var for future use.
>> Next time when page loads, use session vars to show data.
OR
You can store data in Session when user lo-gin && remove it when log out.
Like:
<?php
session_start();
mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$query = "SELECT children, name FROM tree ORDER BY RAND()";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$_SESSION['tree'][] = $row['children'];
}
header("Location: blank.php");
?>
Thanks
Get records into array
and use shuffle command
http://php.net/manual/en/function.shuffle.php
RAND() function in SQL returns Random records from table.
Select * from table_name order by RAND() Limit 10
If you want to persist record in the same order that it first showed, and show it in multiple pages, save the array on fetching in Session variable
I am completely new in the codigniter i just started day befire Yesterday i am having a problem
Here is my snippet of my controller code
$allcalldetails_array = array(
'id' => $row->id,
'customer_id' => $row->customer_id
);
$this->session->set_userdata('logged',$allcalldetails_array);
I want to iterate the $allcalldetails_array in my views please tell me the way to do this
i tried iterating logged but could not get anything .
If i am printing the array in my views like print_r($allcalldetails_array); but this is also disappointing me .Please help me to get back on track .
Thanks
Its not necessary for session variables to be parsed via controller, access it on view directly:
$logged = $this->session->userdata('logged');
print_r($logged);
If you would like data to be send to your view as variables, you should add the corresponding data to your view load.
Controller:
$logged = $this->session->userdata('logged');
$this->load->view('viewfile', $logged);
View
print "logged id:".$id;
best regards.
Jonas
To get the data from session your need to do the following:
// controller logic
$logged = $data['logged_for_view'] = $this->session->userdata('logged'); // since 'logged' is the name you set it to
// more controller logic
$this->load->view('view_name', $data);
// in view
var_dump($logged_for_view); // this is the key of the $data variable you assigned for the view
Regarding the CodeIgniter's documentation :
Data is passed from the controller to the view by way of an array or
an object in the second parameter of the view loading function.
Then you could use something like :
// Controller side
$data['allcalldetails_array'] = array(
'id' => $row->id,
'customer_id' => $row->customer_id
);
$this->load->view('your_view', $data);
// View side
print_r($allcalldetails_array);
// Loop through your array
foreach ($allcalldetails_array as $detail){
// Do something with your $detail.
}
I am using Ion Auth for my codeigniter application and all seems good except for one thing.
I need to display a list of users along with the groups they are in. How can I retrieve the group id of a particular user without making my own models and querying for it.
$this->ion_auth->user($id)->row(); does not retrieve the group id.
Ion Auth has updated and removed the get_user function in the latest version. As a result of this, the below should return the current group id of the logged in user:
$this->ion_auth->get_users_groups()->row()->id
If you're wanting to get the group id of a particular user, you can pass the user id into the get_users_groups method.
get the Object:
$user_groups = $this->ion_auth->get_users_groups($user->id)->result();
Get the name of the group:
$this->ion_auth->get_users_groups($data['id'])->row()->name;
In my case:
$data['groups'] = $this->ion_auth->get_users_groups($data['id'])->row()
You can check the offcial doc about get users groups:
http://benedmunds.com/ion_auth/#get_users_groups
I came across this because I wanted to add a user's group_id(s) to the session upon successful login. In case anyone is interested, here's how I did it (once i managed to figure out where everything was being done).
In ion_auth_model.php, I took the set_session function:
public function set_session($user)
{
$this->trigger_events('pre_set_session');
$session_data = array(
'identity' => $user->{$this->identity_column},
'username' => $user->username,
'email' => $user->email,
'user_id' => $user->id, //everyone likes to overwrite id so we'll use user_id
'old_last_login' => $user->last_login
);
$this->session->set_userdata($session_data);
$this->trigger_events('post_set_session');
return TRUE;
}
and modified it to this:
public function set_session($user)
{
$this->trigger_events('pre_set_session');
$session_data = array(
'identity' => $user->{$this->identity_column},
'username' => $user->username,
'email' => $user->email,
'user_id' => $user->id, //everyone likes to overwrite id so we'll use user_id
'old_last_login' => $user->last_login
);
//get user group ids for user and pass to session
$groups = $this->ion_auth->get_users_groups($user->id)->result();
foreach ($groups as $row){
$session_data['groups'][] = $row->id;
}
$this->session->set_userdata($session_data);
$this->trigger_events('post_set_session');
return TRUE;
}
now it writes an array to the session called groups that is a list of all the groups the user belongs to.
The only other thing I had to do was to modify the logout function in Ion_auth.php (in application/libraries) to make sure the group session variable is unset by adding
$this->session->unset_userdata('groups');
to the list of other unset_userdata() statements.
I know I probably should have just extended the libraries/models to keep the core untouched, but you could take what I did and easily do that.
hope this helps someone.
Rob
Try adding this to ion_auth_model.php
(Or place the query somewhere else)
/**
* get_all_users_with_group
*
* #return array
**/
public function get_all_users_with_group()
{
$this->trigger_events('get_all_users_with_groups');
return $this->db->select(
$this->tables['users'].'.*, '.
$this->tables['users_groups'].'.'.$this->join['groups'].' as group_id, '.
$this->tables['groups'].'.name as group_name, '.
$this->tables['groups'].'.description as group_desc'
)
->join($this->tables['users_groups'], $this->tables['users_groups'].'.'.$this->join['users'].'='.$this->tables['users'].'.id')
->join($this->tables['groups'], $this->tables['users_groups'].'.'.$this->join['groups'].'='.$this->tables['groups'].'.id')
->get($this->tables['users']);
}
use in the controller:
$groups = array(1,2,3,4);
$this->data['list_staff'] = $this->ion_auth->users($groups)->result(); // выбираем всех teachers из зарегистрированных пользователей
foreach ($this->data['list_staff'] as $k => $one_staff)
{
$this->data['list_staff'][$k]->groups = $this->ion_auth->get_users_groups($one_staff->id)->result();
}
and in view use:
<?php foreach($list_staff as $one):?>
<?php foreach ($one->groups as $group):?>
<?php echo $group->description;?>,
<?php endforeach?>
<?endforeach;?>
but what about query to get groups for current logged in user (for example in my profile) I find next decision.
Controller:
$this->data['this_user_groups'] = $this->ion_auth->get_users_groups()->result();
and view just:
<?php foreach ($this_user_groups as $group):?>
<?php echo $group->description;?>,
<?php endforeach?>