Question about Session data and CodeIgniter 3 [duplicate] - php

I want to pass $data from the controller named poll to the results_view however I am getting an undefined variable error.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Poll extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('form');
}
public function index()
{
$this->load->view('poll_view',$data);
}
public function vote()
{
echo "Voting Successfull";
$this->db->insert('votes',$_POST);
}
public function results()
{
echo "These are the results";
//$query = $this->db->get('votes');
$data = "hello";
$this->load->view('results_view', $data);
}
}
Results_view.php
<html>
<?php echo $data; ?>
</html>

$data should be an array or an object: http://codeigniter.com/user_guide/general/views.html
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('results_view', $data);
results_view.php
<html>
<?php
//Access them like so
echo $title.$heading.$message; ?>
</html>

In simple terms,
$data['a'] in controller becomes $a in your view. ($data won't exist in your view, only the index will become available)
e.g.
Controller:
$data['hello']='hellow world';
view:
echo $hello;

You just need to create a array, you using codeigniter right?
Example on controller:
$data['hello'] = "Hello, world";
$this->load->view('results_view', $data);
In de page "results_view" you just have to:
<?php echo $hello;?>
Obs: You can create n datas, just pay attention in the name and make it a array.
ObsĀ²: To use the data use the key of the array with a echo.

The view wouldn't call the data 'data'
The controller would include an associative index (not sure if that's correct nomenclature) for data e.g 'stuff' looking thus $data['stuff']
You'd echo in the view so: echo $stuff; not echo $data;
I am a v lowly code fiddler but do really like CodeIgniter so excuse me if i've got this arse about tit.
One more thing - surely your constructor function is a bit of a waste. All that loading of libraries and helpers is done with the autoload file.

You can create property $data = []; inside CI_Controller(path: system/core/Controller.php) and store all data to show in view. U can load common data like languages, menu, etc in CI_Controller. Also u can add special data for view in controller. (example: $this->data['message'] = "Hello world";)
Finally, u can pass $this->data to view when load view (example: $this->load->view('view_name',$this->data);)
I hope this will help you

you can do it this way
defined array in controller
$data['hello'] = "hello";
and pass variable to view
echo $hello;

If you pass
$data = your code
$this->load->view('your-page', $data);
and get data on your view as
<?php echo $data;?>
It won't work because ci didn't understand this patern. If like to pass value form controller to view so you can try this -
controller -
$data['any-name'] = your values;
$this->load->view('your-page', $data);
then in your view you can get this data by -
<?php echo $any-name;?>
Hope this helps you.

In your controller you can pass
$data['poll'] = "Your results";
In your view you can call
echo $poll;

In controller:
$data["result"] = $this->login_model->get_login(); // Get array value from DB..
$this->load->view('login-form',$data); // Pass the array to view
In view:
print_r($result); // print the array in view file

Ok so I finally solved it. You should really have a model (it helps a lot)
In your model do something like
Model
class poll_model extends CI_MODEL {
function __construct() {
$this-load->database();
}
function get_poll {
$this->db->query("SELECT * FROM table");
$row = $query->row();
$obj = array(
'id' => $row->id
);
return $obj;
}
}
Now if you have more than an id say name of poll # you can add in array.
Now in your controller do
class Poll extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('form');
$this->load->model('poll_model');
}
public function index()
{
$data["a"] = $this->poll_model->get_poll();
$this->load->view('poll_view',$data);
}
And finally in VIEW put
<? echo $a["id"]; ?>
This is a big help. I figured it out by testing and it works for me.

I have seen all above answer so here is what I do when I have to load the data from the controller to my view.
To Pass the Data To the view from the controller:
public function your_controller(){
// Your Necessary Code
// You have the $data, $data2, $data3 to post to the view.
$this->load->view('your_view_directory or view_page',['data'=>$data, 'data2'=>$data2, 'data3'=>$data3... so on ]);
}
And At the View Side You can simply retrieve that data:
To Display You can simply use echo, print, print_r. And if you want to loop over it, you can do that as well.

In controller:
public function product(){
$data = array("title" => "Books", "status"=>"Read","author":"arshad","company":"3esofttech",
"subject":"computer science");
Data From Model to controller
$this->load->model('bookModel');
$result = $this->bookModel->getMoreDetailsOfBook();
**Add *$result* from model to *$data* array**
$data['tableRows'] = $result;
$data from Controller to View
$this->load->view('admin/head',$data);
And to access in view file
views/user.php
<?php echo $data;
foreach($tableRows as $row){ echo
$row['startData']; } ?>

Instead of
$data = "hello";
$this->load->view('results_view', $data);
Do
$data['hello'] = 'hello';
$this->load->view('results_view', $data);
In your controller file and controller will send data having hello as string to results_view and in your view file you can simply access by
echo $hello;

Related

CodeIgniter - Displaying data from a query [duplicate]

I want to pass $data from the controller named poll to the results_view however I am getting an undefined variable error.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Poll extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('form');
}
public function index()
{
$this->load->view('poll_view',$data);
}
public function vote()
{
echo "Voting Successfull";
$this->db->insert('votes',$_POST);
}
public function results()
{
echo "These are the results";
//$query = $this->db->get('votes');
$data = "hello";
$this->load->view('results_view', $data);
}
}
Results_view.php
<html>
<?php echo $data; ?>
</html>
$data should be an array or an object: http://codeigniter.com/user_guide/general/views.html
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('results_view', $data);
results_view.php
<html>
<?php
//Access them like so
echo $title.$heading.$message; ?>
</html>
In simple terms,
$data['a'] in controller becomes $a in your view. ($data won't exist in your view, only the index will become available)
e.g.
Controller:
$data['hello']='hellow world';
view:
echo $hello;
You just need to create a array, you using codeigniter right?
Example on controller:
$data['hello'] = "Hello, world";
$this->load->view('results_view', $data);
In de page "results_view" you just have to:
<?php echo $hello;?>
Obs: You can create n datas, just pay attention in the name and make it a array.
ObsĀ²: To use the data use the key of the array with a echo.
The view wouldn't call the data 'data'
The controller would include an associative index (not sure if that's correct nomenclature) for data e.g 'stuff' looking thus $data['stuff']
You'd echo in the view so: echo $stuff; not echo $data;
I am a v lowly code fiddler but do really like CodeIgniter so excuse me if i've got this arse about tit.
One more thing - surely your constructor function is a bit of a waste. All that loading of libraries and helpers is done with the autoload file.
You can create property $data = []; inside CI_Controller(path: system/core/Controller.php) and store all data to show in view. U can load common data like languages, menu, etc in CI_Controller. Also u can add special data for view in controller. (example: $this->data['message'] = "Hello world";)
Finally, u can pass $this->data to view when load view (example: $this->load->view('view_name',$this->data);)
I hope this will help you
you can do it this way
defined array in controller
$data['hello'] = "hello";
and pass variable to view
echo $hello;
If you pass
$data = your code
$this->load->view('your-page', $data);
and get data on your view as
<?php echo $data;?>
It won't work because ci didn't understand this patern. If like to pass value form controller to view so you can try this -
controller -
$data['any-name'] = your values;
$this->load->view('your-page', $data);
then in your view you can get this data by -
<?php echo $any-name;?>
Hope this helps you.
In your controller you can pass
$data['poll'] = "Your results";
In your view you can call
echo $poll;
In controller:
$data["result"] = $this->login_model->get_login(); // Get array value from DB..
$this->load->view('login-form',$data); // Pass the array to view
In view:
print_r($result); // print the array in view file
Ok so I finally solved it. You should really have a model (it helps a lot)
In your model do something like
Model
class poll_model extends CI_MODEL {
function __construct() {
$this-load->database();
}
function get_poll {
$this->db->query("SELECT * FROM table");
$row = $query->row();
$obj = array(
'id' => $row->id
);
return $obj;
}
}
Now if you have more than an id say name of poll # you can add in array.
Now in your controller do
class Poll extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('form');
$this->load->model('poll_model');
}
public function index()
{
$data["a"] = $this->poll_model->get_poll();
$this->load->view('poll_view',$data);
}
And finally in VIEW put
<? echo $a["id"]; ?>
This is a big help. I figured it out by testing and it works for me.
I have seen all above answer so here is what I do when I have to load the data from the controller to my view.
To Pass the Data To the view from the controller:
public function your_controller(){
// Your Necessary Code
// You have the $data, $data2, $data3 to post to the view.
$this->load->view('your_view_directory or view_page',['data'=>$data, 'data2'=>$data2, 'data3'=>$data3... so on ]);
}
And At the View Side You can simply retrieve that data:
To Display You can simply use echo, print, print_r. And if you want to loop over it, you can do that as well.
In controller:
public function product(){
$data = array("title" => "Books", "status"=>"Read","author":"arshad","company":"3esofttech",
"subject":"computer science");
Data From Model to controller
$this->load->model('bookModel');
$result = $this->bookModel->getMoreDetailsOfBook();
**Add *$result* from model to *$data* array**
$data['tableRows'] = $result;
$data from Controller to View
$this->load->view('admin/head',$data);
And to access in view file
views/user.php
<?php echo $data;
foreach($tableRows as $row){ echo
$row['startData']; } ?>
Instead of
$data = "hello";
$this->load->view('results_view', $data);
Do
$data['hello'] = 'hello';
$this->load->view('results_view', $data);
In your controller file and controller will send data having hello as string to results_view and in your view file you can simply access by
echo $hello;

How to pass data from controller to models in codeigniter

I passed parameter from view to controller via URL. Now I want to send it from controller to model so that I can use it to pick data from tables. Here is my code:
controller:
function view(){
if(isset($_GET['r'])) {
$rank = $_GET['r'];
}
$rank=$this->uri->segment($rank);
$this->load->model('names_rank');
$data=$this->names_rank->get_names($rank);
print_r($rank);
}
model:
function get_names($rank){
$this->db->select('u.*,v.*');
$this->db->from('unit_member u, Vyeo v');
$this->db->where('v.fno = u.fno');
$this->db->where('u.present = ""');
$this->db->where('v.rank', $rank);
$this->db->where('v.date_of_end="0000-00-00"');
$query = $this->db->get();
return $query->result_array();
}
this is the result:
A PHP Error was encountered Severity: Warning Message: Missing
argument 1 for Names_rank::get_names(), called in
C:\xampp\htdocs\unit\application\controllers\names.php on line 32 and
defined
This will work to send to model but your code isn't understandable for me, you re-declare the variable after setting it in the IF? are you trying to print_r() the output from the model?
I think you are trying to achieve this maybe?
function view() {
if(isset($_GET['r'])) {
$rank = $_GET['r'];
}else{
$rank = $this->uri->segment($rank);
}
$this->load->model('names_rank');
$data = $this->names_rank->get_names($rank);
print_r($data);
}
You can pass a Parameter to your model. First you have to call your model within your controller if you not enable it on autoload.
Your Model:
<?php
class AwesomeModel extends CI_Model
{
publif function do_work($param, $anotherParam)
{
//code here
}
}
Then your controller:
<?php
class AwesomeController extends CI_Controller
{
public function __construct()
{
/*
* load in constructor so not need to recall every time you want use it
* second parameter is model renaming (optional)
*/
$this->load->model('AwesomeModel', 'awe');
}
public function pass_data()
{
$this->awe->do_work($param1, $param2);
}
?>
Thats all.

Passing Data from View to Controller (codeigniter)

I am trying to pass some Data using a link from the view to the Controller.
Controller:
public function details(){
echo $this->input->post('data_id');
$data['details'] = $this->wapi_db->details($this->input->post('data_id'));
$data['latest_news'] = $this->wapi_db->latest_news();
$data['main_content'] = "category/details";
$this->load->view('includes/template',$data);
}
View:
<a href=<?php.base_url().'wapi/details?data_id='6'; ?>
You could simply us Uri segmen, just like this:
your View Code for href.
<a href="<?php echo base_url() ?>wapi/details/6";
And to GET the value you passed from view to controller
You should do something like this in your controller
public function details(){
$data_id = $this->uri->segment(3); //this where you get you value from your link
...//rest of your code
}
I recommend you to use this link on your view
<a href=<?php.base_url().'wapi/details/6'; ?>
Then on your controller you just wait for the parameter on the function
public function details($data_id){//<- the parameter you want
$data['details'] = $this->wapi_db->details($data_id);
$data['latest_news'] = $this->wapi_db->latest_news();
$data['main_content'] = "category/details";
$this->load->view('includes/template',$data);
}
If your URI contains more than two segments they will be passed to your method as parameters.
From Codeigniter Controllers Guide
You need to use
$this->input->get('data_id')
because you're passing data via GET method.
So your code should be:
public function details(){
echo $this->input->get('data_id');
$data['details'] = $this->wapi_db->details($this->input->get('data_id'));
$data['latest_news'] = $this->wapi_db->latest_news();
$data['main_content'] = "category/details";
$this->load->view('includes/template',$data);
}
Here the docs: http://www.codeigniter.com/user_guide/libraries/input.html

Using CodeIgniter to populate drop down lists in forms

Being new to CI and PHP, especially arrays, I'm struggling with documentation and tutorials. Please don't point me to the documentation, I have been reading it all day.
As I understand it, I need a view (form), controller and model. The model connects to my default DB connection via a class/function (my DB is where my drop-down list country data is stored), it returns an array, and finally the model parses the array to the form.
Where I struggle is how to parse the array along to the view. Because I'm dealing with 3 files, to output one html file, context is really important, as is syntax. I asked this earlier today and nearly lost my mind as the two answers I got were fragmented and out of context. They were helpful but assumed I knew a lot more than I do.
In other words, please be explicit, because a syntax oversight or knowledge assumption could have me scratching my head for hours. Thanks in advance!
Here's my attempt which isn't working, basically whatever variable I use in the view returns a variable undefined error...
View/Form...
<body>
<?php echo form_open('form'); ?>
<h5>Country</h5>
<?php echo form_dropdown('', $data, '');?>
<div><input type="submit" value="Submit" /></div>
<?php echo form_close() ?>
</body>
My controller...
<?php
class Form extends CI_Controller {
function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('country');
$data['country'] = $this->country->get_country();
$this->load->view('myform', $data);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->database();
$sql = "INSERT INTO donations (country) VALUES (
".$this->db->escape($this->input->post('country')).";
$this->db->query($sql);
echo $this->db->affected_rows();
$this->load->view('formsuccess');
}
}
}
?>
My model...
<?php
class Country extends CI_Model
{
function get_country() {
$this->load->database();
$sql = ('select * from countries');
return $this->db->query($sql)->result();
}
}
?>
Controller
You have $data['country'] with data from database, but your are not adding the $data to the view.
Use $this->load->view('myform', $data); to pass the data to the view.
View
I believe codeigniter extracts the key in the $data:
so simply test in the view what's there var_dump($data); and var_dump($country) and
then build the form_dropdown.
Use echo form_dropdown('country_dropdown', $country, ''); in your view.
Model
Adjust the model to return the array structure needed for form_dropdown.
function get_country() {
$this->load->database();
$sql = ('select * from countries');
$query = $this->db->query($sql);
foreach($query->result_array() as $row) {
$data[$row['id']] = $row['name'];
}
return $data;
}

how to call a function in another controller in code igniter?

I want to call a function in another controller. for example if user try to log in with incorrect parameter then the application will redirect to another controller and passing a variable (array).
class User extends Controller {
function User()
{
parent::Controller();
}
function doLogin()
{
$userData = $this->users->getAuthUserData($user,$password);
if(empty($userData)){
// this is where i need to call a function from another controller
}else{
echo 'logged in';
}
}
}
is it possible passing a variable using redirect() function in url helper?
Yes you can use redirect('othercontroller/function/'.url_encode($data), 'location');
That should work.
edit: you could also put the code in a helper.
<?php
$array = array('foo'=>'bar', 'baz'=>'fubar', 'bar' => 'fuzz');
$json = json_encode($array);
$encoded_json= urlencode($json);
/* now pass this variable to your URL redirect)
/* on your receiving page:*/
$decoded_json= urldecode($encoded_json);
/* convert JSON string to an array and output it */
print_r(json_decode($decoded_json, true));
?>
this code:
takes an array, converts it to a JSON encoded string.
we then encode the $json string using url_encode. You can pass this via the url.
Decode this URL, then decode the JSON object as an associative array.
might be worth a try
If you want to call a function of one controller from another controller then you can use redirect Helper.
For example:
class Logout extends CI_Controller {
function index() {
session_destroy();
redirect('index.php/home/', 'refresh');
}
}
it will call another contoller.

Categories