Im trying to access session throw different controllers OR in different functions in one controller but when i try access the value from different function , variable is NULL
i read some documents (including cakephp session cookbook) and more , but i couldnt understand a bit on how to configure the session before using it.
i have a problem in one controller that im trying to use a session but the value is null after im writing it in another function!?
my other question is how can i avoid writing $this->request->session(); in every function that i want to use session.
CODE :
<?php
namespace App\Controller;
use App\Controller\AppController;
use App\Model\Entity\Answer;
use Cake\ORM\TableRegistry;
class ComlibsController extends AppController {
public function index() {
}
public function getResult(){
$this->viewBuilder()->layout('comlib'); //change the layout from default
$live_req = $this->request->data['searchBox']; // get the question
$session->write('comlib/question' , $live_req);
$query = $this->Comlibs->LFA($live_req); // get the first answer
$shown_answerID = array($query[0]['answers'][0]['id'], '2');
$this->Session->write(['avoidedID' => $shown_answerID]); //avoid the answer that user saw to repeat agian
$this->set('question',$query[0]['question']); // does work
//get the answers result
//and send the array to the
$fields = array('id','answer','rate' , 'view' , 'helpful');
for ($i = 0 ; $i <= 6 ; $i++) {
$this->set('id'.$i,$query[0]['answers'][$i][$fields[0]]);
$this->set('answer'.$i,$query[0]['answers'][$i][$fields[1]]);
$this->set('rate'.$i,$query[0]['answers'][$i][$fields[2]]);
$this->set('view'.$i,$query[0]['answers'][$i][$fields[3]]);
$this->set('helpful'.$i,$query[0]['answers'][$i][$fields[4]]);
}
}
public function moveon() {
$this->render('getResult');
$this->viewBuilder()->layout('comlib');
echo $question = $session->read('comlib/question'); // empty value echo
$avoidedIDs = $session->read('avoidedID');
var_dump($avoidedIDs); // returns NULL WHY ?
$theid = $this->request->here;
$query = $this->Comlibs->LFM($theid,$avoidedIDs,$question);
echo 'imcoming';
}
}
Thanks In Adnvanced
You use these codes for write and read session data:
$this->request->session()->write($name, $value);
$this->request->session()->read($name);
Please read this section in CakePHP book.
Try
$this->session()->write('avoidedID', $shown_answerID);
instead of
$this->session()->write(['avoidedID' => $shown_answerID]);
And try
$avoidedIDs = $this->session()->read('avoidedID');
instead of
$avoidedIDs = $session->read('avoidedID');
Related
I began writing a webapp in Codigniter 4 and currently, i'm stuck with the pagination.
I created a controller, a model an a view to retrieve database entries für usergroups and used CI's built-in pagination-library.
UsergroupsModel:
<?php namespace App\Models;
use CodeIgniter\Model;
class UsergroupsModel extends Model{
protected $table = 'roles';
protected $allowedFields = [];
protected $beforeInsert = ['beforeInsert'];
protected $beforeUpdate = ['beforeUpdate'];
public function getGroups(){
$db = \Config\Database::connect();
$builder = $db->table('roles');
$query = $builder->get();
$results = $query->getResultArray();
return $results;
}
}
Controller (Usergroups):
<?php namespace App\Controllers;
use App\Models\UsergroupsModel;
class Usergroups extends BaseController
{
public function index()
{
//Helper laden
helper(['form','template','userrights']);
$data = [];
$data['template'] = get_template();
$data['info'] = [
"active" => "menu_dash",
"title" => "Dashboard",
"icon" => "fab fa-fort-awesome fa-lg",
"sub" => "Frontend",
];
//Check Permissions
$data['userrights'] = get_userrights(session()->get('id'));
if($data['userrights'][1] == 1)
{
foreach($data['userrights'] as $key => $value){
$data['userrights'][$key] = '1';
}
}
else
{
$data['userrights'] = $data['userrights'];
}
$model = new UsergroupsModel;
$model->getGroups();
$pager = \Config\Services::pager();
$data['usergroups'] = $model->paginate(5);
$data['pager'] = $model->pager;
//Create Views
echo view($data['template'].'/templates/header', $data);
echo view($data['template'].'/backend/navigation');
echo view($data['template'].'/templates/sidebar');
echo view($data['template'].'/backend/usergroups');
echo view($data['template'].'/templates/footer');
}
//--------------------------------------------------------------------
}
In the view, i got my pagination by using
<?= $pager->links() ?>
The default pagination works fine, but i get an URI like https://DOMAIN.DE/usergroups?page=2
In the official Codeigniter 4 docs for the pagination, you can find the following:
Specifying the URI Segment for Page
It is also possible to use a URI segment for the page number, instead of the page query parameter. >Simply specify the segment number to use as the fourth argument. URIs generated by the pager would then >look like https://domain.tld/model/[pageNumber] instead of https://domain.tld/model?page=[pageNumber].:
::
$users = $userModel->paginate(10, ‘group1’, null, 3);
Please note: $segment value cannot be greater than the number of URI segments plus 1.
So in my controller i changed
$data['usergroups'] = $model->paginate(5);
to
$data['usergroups'] = $model->paginate(5,'test',0,2);
and in the view i added 'test' as a parameter.
<?= $pager->links('test') ?>
In the Routes i added
$routes->get('usergroups/(:num)', 'Usergroups::index/$1');
and in the Controller i changed the index-function to
public function index($segment = null)
The URIs generated from the pagination now look like this:
https://DOMAIN.DE/usergroups/2
but it does not change anything in the entries and the pagination itself alway sticks to page 1.
I think, i can not use CI's built in library when switching to segment-URIs and thus i need to create a manual pagination.
Can somebody help me to fix this problem?
I currently had the same problem using segments in my pagination.
After much research I discovered that when you use segments associated with a group name in your case "test" you must assign the segment to the variable $ pager
$pager->setSegment(2, 'nameOfGroup');
You only need to change the first parameter with the segment number that you are using and the second with the name of the group that you are assigning.
It seems like there's a bug in Version 4.0.3. so it can't work out of the box. But i found a way to solve it:
The index-function needs to look like this:
public function index($page = 1)
and
within the Controller, the $data['usergroups'] need to look like this:
$data['usergroups'] = $model->paginate(5, 'test', $page, 2);
with 2 being the segment of the page-number in the URI.
Works like a charm.
I have situation where codeigniter shows database Error Number 1048. It seems Values NULL but when I try to check it usign var_dump($_POST) Values are not NULL.
Controller : Jurusan.php
public function simpan()
{
$this->form_validation->set_rules('code','Kode','required|integer');
$this->form_validation->set_rules('jurusan','Jurusan','required');
$this->form_validation->set_rules('singkatan','Singkatan','required');
$this->form_validation->set_rules('ketua','Ketua','required');
$this->form_validation->set_rules('nik','NIK','required|integer');
$this->form_validation->set_rules('akreditasi','Akreditasi','required');
if($this->form_validation->run() == FALSE)
{
$isi['content'] = 'jurusan/form_tambahjurusan';
$isi['judul'] = 'Master';
$isi['sub_judul'] = 'Tambah Jurusan';
$this->load->view('tampilan_home',$isi);
} else {
$this->model_security->getSecurity();
$key = $this->input->post('code');
$data['kd_prodi'] = $this->input->post['code'];
$data['prodi'] = $this->input->post['jurusan'];
$data['singkat'] = $this->input->post['singkatan'];
$data['ketua_prodi'] = $this->input->post['ketua'];
$data['nik'] = $this->input->post['nik'];
$data['akreditasi'] = $this->input->post['akreditasi'];
$this->load->model('model_jurusan');
$query = $this->model_jurusan->getdata($key);
if($query->num_rows()>0)
{
$this->model_jurusan->getupdate($key,$data);
} else {
$this->model_jurusan->getinsert($data);
}
redirect('jurusan');
}
}
Model : model_jurusan.php
class Model_jurusan extends CI_model {
public function getdata($key)
{
$this->db->where('kd_prodi',$key);
$hasil = $this->db->get('prodi');
return $hasil;
}
public function getupdate($key,$data)
{
$this->db->where('kd_prodi',$key);
$this->db->update('prodi',$data);
}
public function getinsert($data)
{
$this->db->insert('prodi',$data);
}
}
Here is the error shown :
Here is the database structure :
You have a wrong syntax in these lines:
$key = $this->input->post('code');
$data['kd_prodi'] = $this->input->post['code']; // <-- use ('code')
$data['prodi'] = $this->input->post['jurusan']; // <-- use ('jurusan')
Change this to
$this->input->post['array_key'];
this
$this->input->post('array_key');
Read : Input Class in Codeigniter
Well the problem lies in your way of accepting input parameters.
$this->input->post
is a method which accepts the variable name, not an array. So all the input parameters need to be passed as a function parameter to post method. These lines need to be altered to.
$data['kd_prodi'] = $this->input->post('code');
$data['prodi'] = $this->input->post('jurusan');
$data['singkat'] = $this->input->post('singkatan');
$data['ketua_prodi'] = $this->input->post('ketua');
$data['nik'] = $this->input->post('nik');
$data['akreditasi'] = $this->input->post('akreditasi');
Hope this solves the problem.
EDIT:
You did a var_dump($_POST) which works as it is supposed to and it will read the values of the post parameters. So either you fetch the parameters from $_POST array, or you use the $this->input->post() method. But I would suggest using the $this->input->post() method as it provides additional sanitization such as xss attack handling etc, which could be turned on an off from the config.
i have tried your code...it works. I think there some mistakes in your <input> tags, You must use <input name=""> not <input id=""> or something else. Hope it can help you out
You are try to get value from post is wrong. You should use at this way
$_POST['array value'];
I Am trying to insert data in DB,But somehow NULL is inserted in DB
Here Is My Controller
foreach($this->input->post('resume_id') as $key =>$value ){
$ResumeInsert[$key]['resume_keyid'] = $Resume['resume_id'][$key];
$ResumeInsert[$key]['employer_name'] = $Resume['employer_name'][$key];
$ResumeInsert[$key]['start_Date'] = $Resume['start_Date'][$key];
$ResumeInsert[$key]['end_date'] = $Resume['end_date'][$key];
$ResumeInsert[$key]['type_id'] = $Resume['type_id'][$key];
$ResumeInsert[$key]['position'] = $Resume['position'][$key];
$ResumeInsert[$key]['responsibility'] = $Resume['responsibility'][$key];
$ResumeInsert[$key]['Skills'] = $Resume['Skills'][$key];
if(isset($Resume['id'][$key]) ){
$Key_Resume__ExistIDs[]=$Resume['id'][$key];
$ResumeUpdate[$key]=$ResumeInsert[$key];
$ResumeUpdate[$key]['resume_id']=$Resume['id'][$key];
unset($ResumeInsert[$key]);
}
else{
$ResumeInsert[$key]['resume_id'] = $GetLastID;
print_r ($ResumeInsert[$key]);exit;
$GetLastID++;
}
}
$idsToDelete='';
if(empty($ResumeInsert) && empty($ResumeUpdate)){
$idsToDelete=array_diff($Key_Resume_IDs,$Key_Resume__ExistIDs);
}
$status=$this->Resume_model->ProcessData($idsToDelete,$ResumeUpdate,$user_id,$ResumeInsert,$imgInsert,$imgUpdate);
redirect('Resume','refresh');
Here Is My Code Of Model
function ProcessData($idsToDelete,$tbl_resumeUpdate,$user_id,$tbl_resumeInsert,$imgInsert,$imgUpdate){
$this->db->trans_start();
if(!empty($idsToDelete)){
$this->delete_tbl_resume($idsToDelete);
}
if(!empty($tbl_resumeUpdate)){
//echo "up";exit;
$this->update_tbl_resume($tbl_resumeUpdate);
}
if(!empty($tbl_resumeInsert)){
//echo "int";exit;
$this->insert_tbl_resume($user_id,$tbl_resumeInsert);
}
if(!empty($imgInsert)){
$this->insert_tbl_file_paths($imgInsert);
}
if(!empty($imgUpdate)){
$this->update_tbl_file_paths($imgUpdate);
}
return $this->db->trans_complete();
}
This is Insert Query
function insert_tbl_resume($id,$arrtbl_resume){
$this->db->insert_batch('tbl_resume', $arrtbl_resume);
}
In Above Code,Null Value inserted In DB.
when i Print above query,it displays blank
Any Help Please?
You should use form_validation library. I'm giving you an example, you can edit and use it.
In autoload.php, edit $autoload['libraries'] = array(); line to:
$autoload['libraries'] = array('form_validation');
Then, use form_validation in your controller file. For example:
$this->form_validation->set_rules('resume_keyid', 'Resume ID', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->index() // if there is an error, user will redirect to this function
}
else
{
$this->Resume_model->ProcessData();
}
Also please use $this->input->post('resume_keyid', TRUE); structure in your model. "TRUE" means "open XSS filter". Because in CI 3, it comes off as default. If you don't want it, just remove. If you use CI 2, you don't need to add "TRUE".
A few suggestions:
1 - Don't use camelization when you name functions. For example; use process_data() instead of processData()
2 - Check CI Form Validation Document for all details (E.g. all references)
3 - I think you can use $this->db->insert();, just create an array and POST it. If you make it, you'll understand what's wrong.
I want a global array that I can access through controller functions, they can either add or delete any item with particular key. How do I do this? I have made my custom controller 'globals.php' and added it on autoload library.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$notification_array = array();
$config['notification'] = $notification_array;
?>
following function on controller should add new item to my array
function add_data(){
array_unshift($this->config->item('notification'), "sample-data");
}
after add_data adds to the global array, whenever following function is called from client, it should give the updated array to the client.
function send_json()
{
header('content-type: application/json');
$target = $this->config->item('notification');
echo json_encode($target);
}
But my client always gets empty array. How can I make this happen? Please help.
Hi take advantage of OOP, like this
// put MY_Controller.php under core directory
class MY_Controller extends CI_Controller{
public $global_array = array('key1'=>'Value one','key2'=>'Value2'):
public function __construct() {
parent::__construct();
}
}
//page controller
class Page extends MY_Controller{
public function __construct() {
parent::__construct();
}
function send_json()
{
header('content-type: application/json');
$target = $this->global_array['key1'];
echo json_encode($target);
}
}
One solution I came up is to use session, its easy to use and its "fast" you need to do some benchmarking.
As I commented on both answers above/below there is no way you get same data in different controllers just because with each request everything is "reset", and to get to different controller you need to at least reload tha page. (note, even AJAX call makes new request)
Note that sessions are limited by size, you have a limit of 4kb (CodeIgniter stores session as Cookie) but wait, there is way around, store them in DB (to allow this go to config file and turn it on $config['sess_use_database'] = TRUE; + create table you will find more here)
Well lets get to the answer itself, as I understand you tried extending all your controllers if no do it and place some code in that core/MY_Controller.php file
as follows:
private function _initJSONSession() { //this function should be run in MY_Controller construct() after succesful login, $this->_initJSONSession(); //ignore return values
$json_session_data = $this->session->userdata('json');
if (empty($json_session_data )) {
$json_session_data['json'] = array(); //your default array if no session json exists,
//you can also have an array inside if you like
$this->session->set_userdata($ses_data);
return TRUE; //returns TRUE so you know session is created
}
return FALSE; //returns FALSE so you know session is already created
}
you also need these few functions they are self explainatory, all of them are public so you are free to use them in any controller that is extended by MY_Controller.php, like this
$this->_existsSession('json');
public function _existsSession( $session_name ) {
$ses_data = $this->session->userdata( $session_name );
if (empty( $ses_data )) return FALSE;
return TRUE;
}
public function _clearSession($session_name) {
$this->session->unset_userdata($session_name);
}
public function _loadSession($session_name) {
return (($this->_existsSession( $session_name )) ? $this->session->userdata($session_name) : FALSE );
}
the most interesting function is _loadSession(), its kind of self explainatory it took me a while to fully understand session itself, well in a few words you need to get (load) data that are in session already, do something with it ([CRUD] like add new data, or delete some) and than put back (REWRITE) all data in the same session.
Lets go to the example:
keep in mind that session is like 2d array (I work with 4+5d arrays myself)
$session['session_name'] = 'value';
$session['json'] = array('id' => '1', 'name' => 'asok', 'some_array' => array('array_in_array' => array()), 'etcetera' => '...');
so to write new (rewrite) thing in session you use
{
$session_name = 'json';
$session_data[$session_name] = $this->_loadSession($session_name);
//manipulate with array as you wish here, keep in mind that your variable is
$session_data[$session_name]['id'] = '2'; // also keep in mind all session variables are (string) type even (boolean) TRUE translates to '1'
//or create new index
$session_data[$session_name]['new_index'] = FALSE; // this retypes to (string) '0'
//now put session in place
$this->session->set_userdata($session_data);
}
if you like to use your own function add_data() you need to do this
well you need to pass some data to it first add_data($arr = array(), $data = ''){}
eg: array_unshift( $arr, $data );
{
//your default array that is set to _initJSONSession() is just pure empty array();
$session_name = 'json';
$session_data[$session_name] = $this->_loadSession( $session_name );
// to demonstrate I use native PHP function instead of yours add_data()
array_unshift( $session_data[$session_name], 'sample-data' );
$this->session->set_userdata( $session_data );
unset( $session_data );
}
That is it.
You can add a "global" array per controller.
At the top of your controller:
public $notification_array = array();
Then to access it inside of different functions you would use:
$this->notification_array;
So if you want to add items to it, you could do:
$this->notification_array['notification'] = "Something";
$this->notification_array['another'] = "Something Else";
I have the following class:
<?php
class photos_profile {
// Display UnApproved Profile Photos
public $unapprovedProfilePhotosArray = array();
public function displayUnapprovedProfilePhotos() {
$users = new database('users');
$sql='SELECT userid,profile_domainname,photo_name FROM login WHERE photo_verified=0 AND photo_name IS NOT NULL LIMIT 100;';
$pds=$users->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll();
$unapprovedProfilePhotosArray = $rows;
echo 'inside the class now....';
foreach($rows as $row) {
echo $row['userid'];
}
}
}
I can display the data successfully from the foreach loop.
This is a class that is called as follows and want to be able to use the array in the display/view code. This why I added the "$unapprovedProfilePhotosArray = $rows;" but it doesn't work.
$photos_profile = new photos_profile;
$photos_profile->displayUnapprovedProfilePhotos();
<?php
foreach($photos_profile->unapprovedProfilePhotosArray as $row) {
//print_r($photos_profile->unapprovedProfilePhotosArray);
echo $row['userid'];
}
?>
What is the best way for me to take the PHP PDO return array and use it in a view (return from class object). I could loop through all the values and populate a new array but this seems excessive.
Let me know if I should explain this better.
thx
I think you're missing the $this-> part. So basically you're creating a local variable inside the method named unapprovedProfilePhotosArray which disappears when the method finishes. If you want that array to stay in the property, then you should use $this->, which is the proper way to access that property.
...
$pds=$users->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll();
$this->unapprovedProfilePhotosArray = $rows;
...