PHP data array variable not defined in view - php

I am using codeIgniter and I am trying to pass an array of data. I have written like this:
$data['username']="Dumbo";
I also wrote this:
$data['shouts']=$this->Musers->getShout(); // retrieve data from table
Then I write:
$this->load->view("welcome_message", $data);
In view page, I wrote:
<?php echo $username;
foreach ($shouts as $shout)
{
echo $shout->shout;
echo '<br>';
echo $shout->timeStamp;
}
?>
Problem is that while the view did retrieve data from table and display results in view page, an error came up for $data['username'] saying:
"Undefined variable: username"
Why is that? The $data['username'] is already defined! Or what did I do wrong?

<?php echo $data['username']; ?>
If you wrote this, the error will occur.
Correct way is to write like
<?php echo $username; ?>
'username' is the index in the data array, which is passed to the view using the load method
$this->load->view("welcome_message", $data);
If you need to pass an array...
$data['usernames'] = $username_array;
$this->load->view("welcome_message", $data);
Then in the view,
<?php print_r($usernames); ?>

In your view, do this..
$data = array();
$data['username'] = "something";
$data['shouts']=$this->Musers->getShout();

Related

CodeIgniter showing different menu using If statement

I have an error in the variable when I try to get the value it says it was undefined While I have already stored the session of the variable "$level" and sent it to the view but the condition of the variable become undefined, is there anything wrong with the code?
The variable that I get is from the login. Also I have tried to call the $level and it work
I have tried to use foreach and non foreach method still none of these are working
View.php
<?php if($level->level == '1') ?>
<p>Number 1</p>
<?php if($level->level == '2') ?>
<p>Number 2</p>
admin.php
function index(){
$level = $this->session->userdata('level');
$this->load->view('view',$level);
}
Login.php
public function do_login()
{
$u = $this->input->post("user");
$p = md5($this->input->post("pass"));
$cari = $this->model_pesawat->cek_login($u, $p)->row();
$hitung = $this->model_pesawat->cek_login($u, $p)->num_rows();
if ($hitung > 0) {
$data = array('admin_id' => $cari->no_user ,
'admin_user' => $cari->username,
'admin_nama' => $cari->nama,
'level' => $cari->level,
'admin_valid' => TRUE
);
$this->session->set_userdata($data);
redirect('admin','refresh');
}else{
echo "maaf username atau password salah";
}
}
I want the result the if statement will show different value in the view depending on the $level of the user
You need to pass array to the CodeIginter view.
And the array's keys will be used as individual elements in view.
Its similar to extract() function.
So, you should pass $data and add $level into it.
$data['level'] = $level;
$this->load->view('view', $data);
In your view, you can access $level from Controller as $level.
No need to care for $data
In view you can directly use session variable, no need to pass from controller
<p>Number 1</p>
<?php if($this->session->userdata('level') == '2') ?>
<p>Number 2</p>
you should check data in session, whether it's getting stored or not.
echo "<pre>"; print_r($this->session->userdata());

Values not passed from ctp file to controller in CakePHP

I have tried several solution posted in this forum and others as well but it has not helped so far. So I am posting my question finally. BTW, I am using CakePHP 3.6.
I am trying to pass a variable ($product->id) via submit button in view.ctp to my controller action "addit" but I just get "Undefined variable: id " (I have tried addit($id) and addit() either of case I have the same result.)
view.ctp
<p>
<?php echo $this->Form->create('NULL',['url'=>['controller'=>'products','action'=>'addit']]);?>
<?php echo $this->Form->input('id', ['type' => 'hidden', 'value' => $product->id]); ?>
<?php echo $this->Form->button('Add to cart now');?>
<?php echo $this->Form->end();?>
</p>
Controller:Products
public function addit() {
$this->autoRender = false;
if ($this->request->is('post')) {
// $this->Products->addProduct($this->request->data['Cart']['product_id']);
echo "".$this->Products->get($id);//for test
} else {
echo "".$this->Products->get($id);//for test
}
}
According to Cakephp 3.6
All POST data can be accessed using
Cake\Http\ServerRequest::getData(). Any form data that contains a data
prefix will have that data prefix removed. For example:
// An input with a name attribute equal to 'MyModel[title]' is accessible at
$title = $this->request->getData('MyModel.title');
You can get value of $id variable like this:
$id = $this->request->getData('id');
Further Reading: Request Body Data
Is this what you want to do?
$id = $this->request->getData('id');
debug($this->Products->get($id)); //for test

PHP-CODEIGNITER how to get data in session

I want echo my list of trip, when I try print_r the value can show but when I echo the result always
Message: Undefined variable: adventure
Filename: views/profile.php
Line Number: 121
Backtrace:
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/profile.php
Line Number: 121
this is my controller :
public function getListTrip(){
$this->load->model('userModel');
$data['adventure'] = $this->userModel->getTrip()->result_array();
//echo ($data);
$this->load->view('profile', $data);
}
and this is my model :
function getTrip(){
$userId = $this->session->userdata('user_id');
return $this->db->get_where('adventure',['user_id' => $userId]);
}
this is my view
<table>
<?php
foreach ($adventure as $b){
echo "<tr>
<td>$b->name</td>
<td>$b->place</td>
<td>$b->category</td>
</tr>";
}
?>
</table>
so how should I edit my code to make the value show in my page whit echo or foreach not in print_r... thanks a lot
Change your model
function getTrip(){
$userId = $this->session->userdata('user_id');
$query= $this->db->get_where('adventure',['user_id' => $userId]);
return $query->result();
}
Also chnage in your controller
$data['adventure'] = $this->userModel->getTrip()->result_array();
To
$data['adventure'] = $this->userModel->getTrip();
echo is used to output one or more strings, since your $data is an array you see the error, you need to pass data to view and iterate it in the view itself, like:
public function getListTrip(){
$this->load->model('userModel');
$data['adventure'] = $this->userModel->getTrip()->result_array();
//pass data to your view
$this->load->view('yourviewname', $data);
}
For more information check Codeigniter Views
Update
Check if your array is not empty before trying to iterate thru it, like in your view::
<?php
if( !empty($adventure) ) {
foreach($adventure as $b):
?>
<tr>
<td><?php echo $b['name']; ?></td>
<td><?php echo $b['place']; ?></td>
<td><?php echo $b['category']; ?></td>
</tr>
<?php
endforeach;
}
?>
You cannot echo the content of an Array.
So whenever you want to view the Content of an array use print_r($arrayName);
And When you just want to print any variable just use echo $variableName;
I don't see any issue with your code. If you're not using autoloader to load the session library that might be your issue:
$this->load->library('session');
You can check the documentation Codeigniter sessions

Display the result of a function in codeigniter view

In the index function of my controller I am calling getDirContents and I need to display the result of $data['arrDirContents'] in view
public function index()
{
$this->accesscontrol->can_or_redirect('view', 'translation');
$dir = './application/language/english';
$data['arrDirContents']=$this->getDirContents($dir, "~^.+_lang\.php$~i");
$this->output->view('translation/language',$data);
}
Any help on how to get the result of that function in view?
<?php
$dir = './application/language/english';
$data['arrDirContents']=$this->getDirContents($dir, "~^.+_lang\.php$~i");
?>
If this values contents single value means
In View Page just do echo
<?php echo $arrDirContents; ?>
If this values contents multiple value having array value
Do foreach print each variable value
<?php
foreach( $arrDirContents as $directs):
echo $directs;
endforech;
?>
$this->load->vars( array(
'arrDirContents'=>$this->getDirContents($dir, "~^.+_lang\.php$~i")
));

Query not passing with View in Codeigniter

I have the foloowing controller (supernavigationloggedin):
<?php
class Supernavigationloggedin extends CI_Controller {
function index(){
#get current session id
$currentSessionID = $this->session->userdata('session_id');
#get all the account row for the given sessionID
$data['info'] = $this->db->get_where('Client', array('session_id'=>$currentSessionID))->row();
#views
$this->load->view('supernavigationloggedin',$data);
}
}
?>
and the following view named(supernavigationloggedin):
<div id="superNavigation">
<h5><strong>Welcome</strong>, <?php $info->fname; ?> Account Settings</h5>
<div class="clearL"> </div>
</div
>
It keeps throwing an error on line:<h5><strong>Welcome</strong>, <?php echo $info['fname']; ?> <a href="#">Account that Message: >>> Trying to get property of non-object
I've tried : <?php echo $info['fname']; ?> <?php echo $info->fname; ?> but neither seem to work.
It's because $info  is empty and no database request are made. You have to do this this way if you want your query to return an object:
$data['info'] = $this->db->get_where('Client', array('session_id'=>$currentSessionID))->row();
Or this way, if you prefer to get it into an array:
$data['info'] = $this->db->get_where('Client', array('session_id'=>$currentSessionID))->row_array();
This way it should work. row() or row_array() is necessary to execute your query.

Categories