CodeIgniter Session Issues - codeigniter

I set session in a controller function like
$search = array(
'search_count' => count($data['result']),
'projectInfo' => $data['result']
);
$this->session->set_userdata($search);
where $data['result'] is an array;
but if I try to access this variable in other function of same controller it shows nothing:
print_r($this->session->userdata('projectInfo'));
though on using print_r($this->session->userdata('search_count')); it shows correct value.
also if I use print_r($this->session->all_userdata()); in second function of same controller it does not show array value index which I have already set in first function
Array
(
[session_id] => 4adf3a42ee64ffca2b2f273cb293a10a
[ip_address] => 127.0.0.1
[user_agent] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1
[last_activity] => 1347689522
[user_data] =>
)

If I'm correct you can't save arrays into a session without serializing them first.
$search = array(
'search_count' => count($data['result']),
'projectInfo' => $data['result']
);
$this->session->set_userdata($search);
Becomes:
$search = array(
'search_count' => count($data['result']),
'projectInfo' => serialize($data['result'])
);
$this->session->set_userdata($search);
Now if you want to retrieve the array:
$data = unserialize($this->session->userdata('projectInfo'));
print_r($data);
Please note that you should use the database to store sessions when you are setting large amounts of data in a session.
config.php
$config['sess_use_database'] = TRUE;

Thanks I added Native PHP Session Class

Related

How to insert value of my checkbox to different column in database codeigniter

This should be like this
ID|access1|access2|access3|
and values:
1|1|0|1
//myController
$basic_data = array();
$select_access1 = $_POST("select_access1");
$select_access2 = $_POST("select_access2");
$select_access3 = $_POST("select_access3");
$select_access4 = $_POST("select_access4");
$select_access5 = $_POST("select_access5");
$basic_data[] = array('accs_trans_sec'=>$select_access1,'accs_acctng_sec'=>$select_access2, 'accs_admin_sec'=>$select_access3,'accs_dashboard_sec'=> $select_access4, 'accs_reports_sec'=>$select_access5);
$this->RoleModel->saveRole($basic_data);
//myModel
public function saveRole($basic_data)
{
foreach($basic_data as $value) {
$this->db->insert('roles_global_access', $basic_data);
}}
You can set that data to array just like this:
$data = array(
'column1' => 'My Value 1',
'column2' => 'My Value 2',
'column3' => 'My Value 3'
);
$this->db->insert("table_name", $data);
Let's assume that you are getting the values of your checkbox based on your $_POST variables.
Since you've declared $basic_data as array() no need to cast it as $basic_data[].
So on your controller it should be like this:
$basic_data = array(
'accs_trans_sec'=>$select_access1,
'accs_acctng_sec'=>$select_access2,
'accs_admin_sec'=>$select_access3,
'accs_dashboard_sec'=> $select_access4,
'accs_reports_sec'=>$select_access5
);
And your model there's no need to use loop since you are inserting Object data it should look like this:
public function saveRole($basic_data)
{
$this->db->insert('roles_global_access', $basic_data);
return ($this->db->affected_rows() != 1) ? false : true;
}
so basically, if the model returns true then it successfully inserted the data.
To check if data is inserted successfully:
$result = $this->RoleModel->saveRole($basic_data);
if($result == true){
echo ("Successfully inserted!");
}else{
echo ("Problem!");
}
First, you are not getting post data in the correct way. With $_POST have to use square brackets [].
Second, Don't use foreach loop in the model
Get data in the controller like this
$basic_data = array(
'accs_trans_sec' => $_POST['select_access1'],
'accs_acctng_sec' => $_POST['select_access2'],
'accs_admin_sec' => $_POST['select_access3'],
'accs_dashboard_sec' => $_POST['select_access4'],
'accs_reports_sec' => $_POST['select_access5']
);
$this->RoleModel->saveRole($basic_data);
Model
public function saveRole($basic_data){
return $this->db->insert('roles_global_access', $basic_data);
}
You should try this.
Controller:
$this->RoleModel->saveRole($_POST);
Model:
public function saveRole($basic_data){
extract($basic_data);
$dataset = array(
'accs_trans_sec' => $basic_data['select_access1'],
'accs_acctng_sec' => $basic_data['select_access2'],
'accs_admin_sec' => $basic_data['select_access3'],
'accs_dashboard_sec' => $basic_data['select_access4'],
'accs_reports_sec' => $basic_data['select_access5']
);
$this->db->insert('roles_global_access', $dataset);
}

Pagination giving odd error

I'm trying to implement pagination and here is what I have so far.
In my main controller:
public function showIndex()
{
$countries = Country::paginate(5);
return View::make('index')->with('countries', $countries);
}
And in my view I'm simply doing:
<?php print_r($countries); ?>
However, that outputs an insanely long error, too long to post here in full:
Illuminate\Pagination\Paginator Object ( [factory:protected] =>
Illuminate\Pagination\Factory Object ( [request:protected] =>
Illuminate\Http\Request Object ( [json:protected] => [sessionStore:protected]
=> [attributes] => Symfony\Component\HttpFoundation\ParameterBag Object (
[parameters:protected] => Array ( ) ) [request] =>
Symfony\Component\HttpFoundation\ParameterBag Object ( [parameters:protected]
=> Array ( ) ) [query] => Symfony\Component\HttpFoundation\ParameterBag
Object ( [parameters:protected] => Array ( ) ) [server] =>
Symfony\Component\HttpFoundation\ServerBag Object ( [parameters:protected] =>
Array ([HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0)
Gecko/20100101 Firefox/36.0 [HTTP_ACCEPT] =>
text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5 [HTTP_ACCEPT_ENCODING] => gzip,
deflate [HTTP_COOKIE] =>
What am I doing wrong? Am I missing something?
I'm going to post an answer here for the sake of clarification. The "error" you're getting isn't an error at all. It is, however, insanely long because it's printing recursively the entire collection returned from the ::paginate(5) method. If you scroll to the very bottom of this print_r statement, you should be able to make our your result set. For example, look for the id of one of your results and you should see something like Array ([id] => 1 [column_2] => x [column_3] => y ... where column_N are the names of the columns in your table.
Easiest rule of thumb when using Laravel:
If you return a collection, use a foreach loop.
And by that I mean if you use the methods ->get() or ->paginate(), go through your results using #foreach($items AS $item).
Hope that provided some clarification.
To answer my own question, all I had to do was add a loop in the view to loop through the database results:
#foreach ($countries as $country)
<div class="title">{{ $country->name }}</div>
#endforeach
{{ $countries->links() }}

Use Array Data in CodeIgniter Model as SQL?

In my controller, I am passing data to the model using the following code:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
var_dump($data);
$this->Login_model->insert_entry($data);
In my model, what I want to do is use the gid value as part of an SQL statement, like so:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = $gid');
Obviously this doesn't work, so I'm just wondering how I get the gid from $data and use it in my SQL statement?
Tested using
$get_gid = $this->db->where('gid', $data['gid'])->get('users');
print_r($get_gid);
However output is:
CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id]
=> Resource id #33 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0
[num_rows] => 0 [row_data] => )
Did you try gid = $data['gid']
I assume that yours model method looks like this:
insert_entry($data)
{
here active record or query...
}
If yes try to display query to see if $data['gid'] is visible there
You can try it by
$this->db->get_compiled_select();
Or after query runs
$this->db->last_query();
Try this way:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
$gid = $data['gid'];
$this->db->where('gid',$gid);
$this->db->from('users');
$query = $this->db->get();
if($query)
{
//you can return query or you can do other operations here like insert the array data
//$this->db->insert('yourtable',$data);
return $query;
}
else
{
return FALSE;
}
You can try:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = '.$data['gid'].');
You just Forget after query $query->result().

Session not set in codeigniter

I have set the session like this
$loc_details = array(
'maincity_id' =>$maincity_id,
'mainzoneid' => $mainzoneid,
'mainproductid' => $productid,
);
$this->session->set_userdata($loc_details);
Here i have retrieved the values like this
$maincity_id=$this->session->userdata('maincity_id');
//$mainzone_id=$this->session->userdata('mainzone_id');
$mainproduct_id=$this->session->userdata('mainproductid');
but if i see the output the session is not set can any one help with this
You need to do like this..........
$loc_details = array(
'maincity_id' =>$maincity_id,
'mainzoneid' => $mainzoneid,
'mainproductid' => $productid,
);
$this->session->set_userdata('loc_details',$loc_details);
$loc_details = $this->session->userdata("loc_details");
$maincity_id = $loc_details['maincity_id'];
$mainproduct_id = $loc_details['mainproductid'];

Cakephp: choose which data to save after login

I cannot understand how to choose which user data to save after login. I have noticed that I can only change the recursivity of the model, but I cannot choose individual fields to use.
For example, normally Cakephp saves in session all user fields except the password, even the data that I don't need and I do not want stored.
If I increase the recursion, Cakephp saves all the fields of related models.
Is there a way as for the "fields" parameter of the Model find method?
I know that after login I can recover the data that I miss and add them in session, merging to those already stored, but I want to avoid making another query and find a more elegant solution, if it exists.
Thanks.
As of Cake 2.2, you can add a contain key to your authentication options to pull related data. Since the contain key accepts a fields key, you can restrict the fields there:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'contain' => array(
'Profile' => array(
'fields' => array('name', 'birthdate')
)
)
)
)
)
);
If you want to change the fields the user model searches for, you can extend the authentication object you're using. Generally the users table contains a minimal amount of information, so this isn't usually necessary.
However, I'll give an example anyway. We'll use the FormAuthenticate object here, and use most of the _findUser method code from the BaseAuthenticate class. This is the function that Cake's authentication system uses to identify the user.
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class MyFormAuthenticate extends FormAuthenticate {
// overrides BaseAuthenticate::_findUser()
protected function _findUser($username, $password) {
$userModel = $this->settings['userModel'];
list($plugin, $model) = pluginSplit($userModel);
$fields = $this->settings['fields'];
$conditions = array(
$model . '.' . $fields['username'] => $username,
$model . '.' . $fields['password'] => $this->_password($password),
);
if (!empty($this->settings['scope'])) {
$conditions = array_merge($conditions, $this->settings['scope']);
}
$result = ClassRegistry::init($userModel)->find('first', array(
// below is the only line added
'fields' => $this->settings['findFields'],
'conditions' => $conditions,
'recursive' => (int)$this->settings['recursive']
));
if (empty($result) || empty($result[$model])) {
return false;
}
unset($result[$model][$fields['password']]);
return $result[$model];
}
}
Then use that authentication and pass our new setting:
public $components = array(
'Auth' => array(
'authenticate' => array(
'MyForm' => array(
'findFields' => array('username', 'email'),
'contain' => array(
'Profile' => array(
'fields' => array('name', 'birthdate')
)
)
)
)
)
);
I just spent a while on this problem, only to find out that a 'userFields' option has been implemented as of Cake 2.6
Have a look at the docs here:
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html

Resources