accessing array in array data pass from controller to view of codeigniter - codeigniter

I have this following code in my controller. I want to print the data i have my array.. should it be double forloop or foreach?
CONTROLLER:
public function index()
{
$in_cart = array();
if (!isset($_SESSION['cartProducts'])){
$in_cart['list'] = "No Products";
}
else{
foreach ($_SESSION['cartProducts'] as $key => $value) {
$in_cart[$key] = $this->shopmod->get_one_data($key);
}
$cart['list'] = $in_cart;
}
$this->load->vars($cart);
$data['cart'] = $this->load->view('shop/cart', '', TRUE);
$this->load->view('layout/default', $data);
}
VIEW:
<?php if(is_array($list)): ?>
<?php foreach($list as $row):?>
<tr>
<td><?=$row->name?></td>
</tr>
<?php endforeach ?>
<?php endif;?>
but i have this following error:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: shop/cart.php
Line Number: 18
anyhelp guys? :(

I see you are using Code igniter (nice!)
I would do the following to ensure the $key is taking 'name'
public function index() {
foreach ($_SESSION['cartProducts'] as $key => $value) {
echo $key;
} }
Then
public function index() {
$in_cart = array();
if (!isset($_SESSION['cartProducts'])){
$in_cart['list'] = "No Products";
}
else{
foreach ($_SESSION['cartProducts'] as $key => $value) {
$in_cart[$key] = $this->shopmod->get_one_data($key);
}
}
$this->load->vars($cart);
$data['cart'] = $this->load->view('shop/cart', '', TRUE);
$data['list'] = $in_cart;
$this->load->view('layout/default', $data); }

PHP is telling you exactly what is wrong.
You are trying to access the name property of the $row array when the -> syntax is specifically reserved for objects.
To access array values, you use square brackets and keys: <?=$row['name']?>
Helpful hint to understand - What you're doing is quasi-equivalent to: 7->name, insofar as the left value (7) has no idea how to use the arrow syntax. It's reserved for when the left value is an object. Not an integer, or in your case, an array.
Update after your comment:
You would get at the data like this:
<? foreach($row['list'] as $r):?>
<tr>
<td><?=$r[0]->name;?></td>
</tr>
<? endforeach;?>

Related

Codeigniter db->where() not working in foreach loop

On my view I need to be able to get the hidden banner_image_id and use that in my $this->db->where('banner_image_id', $id) on my model function
When I update the image. It does not update to the correct row. Instead it update all rows with the same filename.
Question: On my model how can I make sure that my $this->db->where('banner_image_id', $id) updates correct rows.
I have done a vardump($id) and result is string(2) "63" which is correct but still updates every row the same. I tried update_batch also no luck.
Model Function
public function edit_banner_image($file_name) {
$banner_image_id = $this->input->post('banner_image_id');
if (isset($banner_image_id)) {
foreach ($banner_image_id as $id) {
//var_dump($id);
//exit;
$data = array('banner_id' => $this->uri->segment(4),'banner_image' => $file_name);
$this->db->where('banner_image_id', $id);
//$this->db->where_in('banner_image_id', $id); // Tried No Luck
//$this->db->or_where_in('banner_image_id', $id); // Tried No Luck
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
}
View Table
<table>
<tbody>
<?php foreach ($banner_images as $img) { ?>
<tr>
<td>
<?php echo $img['banner_image_id'];?>
<input type="hidden" name="banner_image_id[]" value="<?php echo $img['banner_image_id'];?>">
</td>
<td>
<input type="file" name="banner_image[]" multiple size="20">
</td>
<td>
<img src="<?php echo base_url() . 'uploads/' . $img['banner_image'];?>" />
<input type="hidden" name="banner_image" value="<?php echo $img['banner_image'];?>">
</td>
</tr>
<?php }?>
<tbody>
</table>
Try to concatenate the id numbers in foreach loop and pass it where function at once.
Assuming that your id numbers are array(1,2,5,6).
public function edit_banner_image($file_name) {
$banner_image_id = $this->input->post('banner_image_id');
if (isset($banner_image_id)) {
$bid = 'IN(';
foreach ($banner_image_id as $id) {
$bid .= $id . ',';
}
$bid = substr($bid, 0, -1) . ')'; //remove last comma and add closing paranthesis.
//The content of the variable $bid would be like
//IN(1,2,5,6)
$data = array('banner_id' => $this->uri->segment(4),'banner_image' => $file_name);
$this->db->where('banner_image_id', $id);
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
Another Suggestion:
Convert $banner_image_id to a normal array in case of it is an associative array.
public function edit_banner_image($file_name) {
$banner_image_id = $this->input->post('banner_image_id');
$bid = array();
if (isset($banner_image_id)) {
foreach ($banner_image_id as $id) {
$bid[] = $id;
}
$data = array('banner_id' => $this->uri->segment(4),
'banner_image' => $file_name);
$this->db->where_in('banner_image_id', $bid);
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
I suggest you to make convertion in the controller section, not in model. The lines ending with // should be in the controller. You can easily pass $bid to edit_banner_image($file_name, $bid) function then.
public function edit_banner_image($file_name, $bid) {
$banner_image_id = $this->input->post('banner_image_id'); //
$bid = array();//
if (isset($banner_image_id)) {//
foreach ($banner_image_id as $id) { //
$bid[] = $id;//
}
$data = array('banner_id' => $this->uri->segment(4),
'banner_image' => $file_name);
$this->db->where_in('banner_image_id', $bid);
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
Thus, you will have more readable code.

codeigniter grabbing array from database

I'm new to codeigniter and followed the guides but seem to be missing something. I have a simple database with customer records in it. My first goal in codeigniter is to simple list all my customers.
here is my controller:
public function index()
{
$this->load->model('HomeModel'); //loads the HomeModel model
$data = $this->HomeModel->function1(); //loads the function (function1) from the model
$this->load->view('index', $data);
}
Here is my model:
public function function1()
{
$query = $this->db->get('work_orders');
return $query->result();
}
here is my view:
<table class="table table-bordered table-striped table-highlight" id="invoice-details">
<thead>
<tr>
<th>Work Order ID</th>
<th>Status</th>
<th>Description</th>
</tr>
</thead>
<?php
foreach ($data->result() as $row);?>
<tr class="even gradeC">
<td><a href="/WorkOrders/viewWo/<?php echo $row['id']; ?>">
<?php echo $row['id']; ?></a></td>
<td><?php echo $row['status']; ?></td>
<td><?php echo Logic\System\Lib\Helper::trunc(htmlentities($row['description']), 8); ?></td>
</tr>
<?php endforeach; ?>
</table>
Change on model :
public function function1()
{
$query = $this->db->get('work_orders');
//return $query->result();
return $query->result_array();
}
Change on controller :
public function index()
{
$this->load->model('HomeModel');
//$data = $this->HomeModel->function1();
$data['result'] = $this->HomeModel->function1();
$this->load->view('index', $data);
}
Change on view :
//foreach ($data->result() as $row);
if(is_array($result)&&!empty($result))
foreach ($result as $row);
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. Here is an example using an array:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
Views : Codeigniter User Guide
And Since you are using array on your view like $row['id'], you got to use result_array on model to return result set array:
This function returns the query result as a pure array, or an empty array when no result is produced. Typically you'll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
Generating Query Results : Codeigniter
You can use $this->db->join();
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
Produces:
SELECT * FROM blogs
JOIN comments ON comments.id = blogs.id
Go through active record class guide .
Active Record Class
In ur controller,u must pass the values as subarray of data array$data['result'].After which u can simply call it in view as $result .
Controller
$data['result'] = $this->HomeModel->function1();
And In view,
foreach ($result as $row){
<?php echo $row->id; ?>
..
}

Undefined variable: query - codeigniter

I am getting the message:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: query
Filename: views/main.php
Line Number: 12
This is the code for my controller:
function get_all(){
$this->load->model('book_model');
$this->load->library('table');
$this->load->helper('html');
$data['query'] = $this->books_model->books_getall();
$this->load->view('main', $data);
}
And this is my view:
<h1> List of books in library</h1>
<table border="1"/>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Information</th>
<th>Publisher</th>
<th colspan="2">Action</th>
</tr>
<?php
if(is_array($query)){
foreach ($query as $row){
echo "<tr>";
echo "<td>".$row->id."</td>";
echo "<td>".$row->title."</td>";
echo "<td>".$row->author."</td>";
echo "<td>".$row->information."</td>";
echo "<td>".$row->publisher."</td>";
echo "<td>".anchor('book/input'.$row->id,'Edit')."</td>";
echo "<td>".anchor('book/delete'.$row->id,'Delete')."</td>";
echo "</tr>";
}
}
?>
</table>
Thanks in advance for any help
Edit: This is my model code:
function get_all(){
$this->load->database();
$query = $this->db->get('books');
return $query->result();
}
From what I can see, line 12 appears to be this line:
if(is_array($query)){
And the error message is saying that $query is undefined. When you pass $data['query'] through to the view, that becomes $query.
I note your model is also returning $query->result(). This is not correct - result() should be used inside a loop to loop through the results, and you can use num_rows() to test for more than zero results, as in this example:
Model
function example()
{
$query = $this->db->get('books');
return $query;
}
Controller
$this->load->model('book_model');
$this->load->library('table');
$this->load->helper('html');
$data['query'] = $this->books_model->books_getall();
$this->load->view('main', $data);
View
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
// Do stuff here on each $row
}
}
I suggest you take a look at this part of CodeIgniter's documentation, which is actually very good.

passing multiple queries to view with codeigniter

I am trying to build a forum with Codeigniter.
So far i have the forums themselves displayed and the threads displayed, based on the creating dynamic news tutorial.
But that is 2 different pages, i need to obviously display them into one page, like this:
Forum 1
- thread 1
- thread 2
- thread 3
Forum 2
- thread 1
- thread 2
etc.
And then the next step is obviously to display all the posts in a thread. Most likely with some pagination going on. But that is for later.
For now i have the forum controller (slimmed version):
<?php
class Forum extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('forum_model');
$this->lang->load('forum');
$this->lang->load('dutch');
}
public function index()
{
$data['forums'] = $this->forum_model->get_forums();
$data['title'] = $this->lang->line('title');
$data['view'] = $this->lang->line('view');
$this->load->view('templates/header', $data);
$this->load->view('forum/index', $data);
$this->load->view('templates/footer');
}
public function view($slug)
{
$data['forum_item'] = $this->forum_model->get_forums($slug);
if (empty($data['forum_item']))
{
show_404();
}
$data['title'] = $data['forum_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('forum/view', $data);
$this->load->view('templates/footer');
}
}
?>
And the forum_model (also slimmed down)
<?php
class Forum_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_forums($slug = FALSE)
{
if ($slug === FALSE)
{
$query= $this->db->get('forum');
return $query->result_array();
}
$query = $this->db->get_where('forum', array('slug' => $slug));
return $query->row_array();
}
public function get_threads($forumid, $limit, $offset)
{
$query = $this->db->get_where('thread', array('forumid', $forumid), $limit, $offset);
return $query->result_array();
}
}
?>
And the view file
<?php foreach ($forums as $forum_item): ?>
<h2><?=$forum_item['title']?></h2>
<div id="main">
<?=$forum_item['description']?>
</div>
<p><?=$view?></p>
<?php endforeach ?>
Now that last one, i would like to have something like this:
<?php foreach ($forums as $forum_item): ?>
<h2><?=$forum_item['title']?></h2>
<div id="main">
<?=$forum_item['description']?>
</div>
<?php foreach ($threads as $thread_item): ?>
<h2><?php echo $thread_item['title'] ?></h2>
<p><?=$view?></p>
<?php endforeach ?>
<?php endforeach ?>
But the question is, how do i get the model to return like a double query to the view, so that it contains both the forums and the threads within each forum.
I tried to make a foreach loop in the get_forum function, but when i do this:
public function get_forums($slug = FALSE)
{
if ($slug === FALSE)
{
$query= $this->db->get('forum');
foreach ($query->row_array() as $forum_item)
{
$thread_query=$this->get_threads($forum_item->forumid, 50, 0);
}
return $query->result_array();
}
$query = $this->db->get_where('forum', array('slug' => $slug));
return $query->row_array();
}
i get the error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: models/forum_model.php
Line Number: 16
I hope anyone has some good tips, thanks!
Lenny
*EDIT***
Thanks for the feedback.
I have been puzzling and this seems to work now :)
$query= $this->db->get('forum');
foreach ($query->result() as $forum_item)
{
$forum[$forum_item->forumid]['title']=$forum_item->title;
$thread_query=$this->db->get_where('thread', array('forumid' => $forum_item->forumid), 20, 0);
foreach ($thread_query->result() as $thread_item)
{
$forum[$forum_item->forumid]['thread'][]=$thread_item->title;
}
}
return $forum;
}
What is now next, is how to display this multidimensional array in the view, with foreach statements....
Any suggestions ?
Thanks
You are using row_array() hence your error, change your get_forums() to:
$thread_query=$this->get_threads($forum_item['forumid'], 50, 0);
But I believe you should actually be using result_array() since you want a list of all forums.

I have a question about using form_dropdown()

I have a question about using form_dropdown().
table:category
cat_id
cat_name
Controller:
function index()
{
$this->load->model('category_model');
$data['category'] = $this->category_model->cat_getallcat();
$this->load->view('category_input',$data);
}
Model:category_model
function cat_getallcat()
{
$this->load->database();
return $this->db->get('category')->result();
}
View:
<?php
$this->load->helper('form');
echo form_open('send');
$list[''] = 'Please select a Category';
foreach($query as $row)
{
$list[$row->cat_id] = ucfirst(htmlspecialchars($row->cat_name));
}
echo form_dropdown('category', $list);
echo form_close();
?>
error obtained:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/category_input.php
Line Number: 28
the ->result() will return the first row only, so this function is what you want to loop over.
Model
function cat_getallcat()
{
$this->load->database();
return $this->db->get('category');
}
View
foreach($query->result() as $row)
{
$list[$row->cat_id] = ucfirst(htmlspecialchars($row->cat_name));
}
EDIT:
Also, you are sending the result as $data['category'] then trying to access it as $query. So really the foreach would be foreach($category->result() as $row) in this example
You are asking foreach to loop over $query, but I you haven't set $query as a variable anywhere that I can see.
Since you set $data['category'] to hold your query result() in your controller, you need to loop over $category in the view:
foreach($category as $row)
{
$list[$row->cat_id] = ucfirst(htmlspecialchars($row->cat_name));
}

Resources