get variable from another function in codeigniter - php

I want to ask about how to get data from variables that are in other functions but still in the same controller....
this is the function, where the variable will be sent named $whs
function deliver($whs_id)
{
$whs = $whs_id; // here is variable to pass
$this->cart->destroy();
$this->template->set_title('Package');
$this->breadcrumbs->push('Package', '/Package');
$this->breadcrumbs->push('Create Package', '/pacakge/index');
$data['item'] = $this->MY_Model->join2_where('box_stock','product_code','box_product','product_code','whs_id',$whs_id)->result();
$this->template->load('templates/Template', $this->folder.'/item', $data);
}
function save()
{
$whs2 =$whs; // i will get data in here
// judul halaman
$this->template->set_title('Package');
// Breadcrumbs
$this->breadcrumbs->push('Package', 'package');
$this->breadcrumbs->push('Save', '/package/save');
// JS Init
$js_init = "";
}
how can I get the data that is in another function in the same controller ?

Related

PHP variables in function argument is not working

I've retried solving this, by using a condition and a default attribute as recommended.
User-generated data is declared before to $Variable_1:
<?php
$Variable_1 = 'abc123!' //The user inputs the data
if ($booleanvalue == true) { // User selects if they've put data
name($user_data, $Variable_0 = $Variable_1 );
}
//Then the function will use the user's data from $Variable_1
function name($user_data, $Variable_0 = null) {
//Other code...
}
$Variable_2 = name($user_data);
$data['variable_2'] = $Variable_2;
?>
Is it possible to have $Variable_0 pre-declared and then put as an argument?
you have a few mistakes in your code. and I don't think that you can use a function named name.
you could do it this way for example:
<?php
$Variable_1 = 'abc123!';
function test($data) {
global $Variable_1;
//Other calculations...
return $Variable_1 . $data;
}
$testdata = "huhu";
$Variable_2 = test($testdata);
$data['variable_2'] = $Variable_2;
echo $data['variable_2'];
?>
I agree with the comment by El_Vanja, but you can access a global variable through the magic $GLOBALS array anywhere.
<?php
// what you might actually want
function name($variable = 'abc123!')
{
// if no value is passed into the function the default value 'abc123!' is used
}
$variable = 'abc123!';
// what you could do
function name2($variable)
{
// $variable can be any value
// $globalVariable is 'abc123!';
$globalVariable = $GLOBALS['variable'];
}
I'd also like to point out that currently you have no way of controlling what type of data is passed to the function. You might consider adding types.
<?php
<?php
// string means the variable passed to the function has to be a ... well string
function name(string $variable = 'abc123!'): void
{
// void means the function doesn't return any values
}
name(array()); // this throws a TypeError

i need some help about using sessions in code igniter

I am using codeigniter. I used session variable to store a id in a function and get the stored value in another function. I have a controller file which is given below:
public function select_service($id)
{
$this->load->library('session');
$this->session->unset_userdata('employee');
$this->session->set_userdata('employee', ['total'=>$id]);
// $id = $this->uri->segment(4);
$data['service'] = $this->add_service_model->get_services();
$data['main_content'] = 'admin/service_limitation/service_view';
$this->load->view('includes/template', $data);
}
In the above code I get the id from a form and store in the session variable
public function services()
{
//here i need to get the session variable employee['total']
$id = $this->uri->segment(5);
$data_to_store=array('employee_id'=>$id,'service_id'=>$this->input->post("services"));
$this->add_service_model->save($data_to_store);
$data['addservice'] = $this->add_service_model->get_addservices();
$data['main_content'] = 'admin/service_limitation/newview';
$this->load->view('includes/template', $data);
}
In this function service I need to retrieve the stored value. both functions are in same controller. can some one help me with the code?
Manuall
Auto load the session library. This way the session is always loaded.
when setting the id do: $this->session->set_userdata('employee', $id);
when you want to get that id user $id = $this->session->userdata('employee');

Output two array in one view (Kohana)

I have one controller which need to output in one view file and $_GET param.
Controller code is:
public function action_register_final() {
//Detect view file
$block_center = View::factory('pages/v_register_final');
$block_center = $this->request->param('user_id');
//Detect block
$this->template->block_center = array($block_center);
}
But this code is output only $_GET param... if i remove $block_center = $this->request->param('user_id'); view is loading good and output. I know i replace $block_center but how I can to output both values.
Thx.
Watch. You overwrite your variable. I think you need this:
public function action_register_final()
{
// Detect view file
$this->template = View::factory('pages/v_register_final');
$this->template->block_center = array($this->request->param('user_id'));
}
Or.
public function action_register_final()
{
// Detect view file
$this->template = View::factory('pages/v_register_final');
$block_center = this->request->param('user_id');
$this->template->block_center = array($block_center);
}
Not tested. This is what you need? Where is your second array? Try merge.

How to pass data from one function to another in codeigniter by using session?

Am trying to pass some data from one function to another when i set the data into session and print the session data i get the correct data, but whe trying to use the data in another function i get the word "Assets" i dont know where this word come from. Session library is auto loaded.Any help please.
These are my codes:
First function:
$client_id = $this->uri->segment(3);
$sess_array = array(
'cl_id' => $client_d,
'selected_client'=>TRUE,
);
$this->session->set_userdata('selected_client',$sess_array);
Second function:
$client_sess = $this->session->userdata('selected_client');
$client_id= $client_sess['cl_id'];
Try this i think this will give you some idea.
function one(){
$client_id = $this->uri->segment(3);
$sess_array = array(
'cl_id' => $client_d,
'selected_client'=>TRUE,
);
$this->two($sess_array);
}
function two($id){
$client_id= $id;
}
Here is what the Model looks like:
function getResponse($gettingresponse)
{
$enrollresponse=$gettingresponse['sendresponse'];
return $enrollresponse;
}
The Controller is as follows:
public function Register()
{
   $this->load->view('firstview');
   $this->load->view('secondview');
   if($_POST) {
       $gettingresponse=array(
           'sendresponse'=>$_POST['source'],
           'receiverresponse'=>$_POST['destination']
       );
       $registration_confirm=$this->systemModel->responselogin($gettingresponse);
       $resposeflag=$this->systemModel->getEmail($gettingresponse);
       $data['resposeflag']=$gettingresponsevalue;
       if($registration_confirm){
           $this->token($data);
       }
   }
   $this->load->view('thirdview');
}
public function token($data=array())
{
   $this->load->view('firstview');
   $data['resposeflag'];
   $this->load->view('token',$data);
   $this->load->view('thirdview');
}
The following View shows the data that has been passed between the functions of the Controller.
<?php
echo form_input(array('name'=>'source','readonly'=>'true','value'=>$resposeflag));
?>

Dynamic global array in codeigniter

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";

Categories