codeigniter grabbing array from database - codeigniter

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; ?>
..
}

Related

how to view individual field of the table in codeigniter

I have created following table in mysql
I want to retrieve one of the field i.e abstract or author or Title by using id dynamically in view field.
These are my model, controller and view code.
Model:This is my model
$this->db->select("*");
$this->db->limit(10);
$this->db->from("abcde");
$query = $this->db->query("SELECT * FROM abcde ORDER BY DocumentID ASC");
Controller: this is my controller here
$this->load->model("Sample_model");
$data["fetch_data"] = $this->Sample_model->fetch_data();
$data['view']='services_view';
$this->load->view('load_view', $data);
return $query;
View:This is my view page
<?php
if($fetch_data->num_rows() > 0)
{
foreach($fetch_data->result() as $row)
{
?>
<tr>
<td><?php echo $row->Abstract
</tr>
<?php
}
}
?>
</table>
The above view is displaying all the record of abstract.I want to use ID in view so that i can get specific abstract in one line.
for example display abstract where id=1 or display author where id 3.Important point is here that i want to use id in view of the codeigniter. I will be grateful to you for your help.
Hope this will help you :
You can use custom helper to get the desired result
Add a file in your helpers folder name custom_helper.php and autoload with autoload.php like this :
$autoload['helper'] = array('custom');
In your custom_helper.php add a function like this :
function get_abstract($id)
{
$ci = & get_instance();
$query = $ci->db->get_where('abcde',['id' => $id]);
return $query->row()->abstract;
}
in your view call this get_abstract function like this:
<?php
if($fetch_data->num_rows() > 0)
{
foreach($fetch_data->result() as $row)
{
?>
<tr>
<!-- get abstract by id like this -->
<td><?php echo get_abstract($row->id);?></td>
</tr>
<?php }
}?>
Update : your controller should be like this :
public function services()
{
$this->load->model("Sample_model");
$data["fetch_data"] = $this->Sample_model->fetch_data();
$data['view']='services_view';
$this->load->view('load_view', $data);
}
Your model fetch_data should be like this :
function fetch_data()
{
$this->db->order_by("DocumentID" ,"ASC");
$this->db->limit(1);
$query = $this->db->get('prlaps');
return $query;
}
Update for View with using row() instead of result():
<?php
if($fetch_data->num_rows() > 0)
{
$row = $fetch_data->row();
echo get_abstract($row->id);
}?>

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.

Undefined variable, how to retrieve data from database in codeigniter?

My model is:
function get_all_pages(){
$query= $this->db->query("SELECT Title FROM news");
return $query->result_array();
}
My view is:
<table cellpadding="0" cellspacing="0">
<tr>
<th>Title</th>
</tr>
<?php
$count=1;
if(!empty($content)) {
foreach ($content as $content1)
{
?>
<tr>
<td align="left"><?php echo $content1['Title']; ?></td>
</tr>
<?php
}
} else{?>
<tr>
<td align="center" colspan="4"><?php echo "No Record Added Yet!!!";?></td>
</tr>
<?php }?>
</table>
My controller is:
public function manage_news()
{
$this->load->model('users_model');
$result_nb = $this->users_model->get_all_pages();
$data['content'] = $result_nb;
$data['page_title']="Manage Pages";
$this->load->view("manage_news",$data);
}
I am using codeigniter. my exact error is:
Call to undefined method users_model::get_all_pages()
how can i fix this error? i want the title row data to appear in a table (from the db)
Q: use Correct naming structure for CI? Which version do u use?
Filename
models/user_model.php
Examples (for demo purpose)
<?php
class User_model extends CI_Model {
// example one
function get_all_pages() {
$query = $this->db->query("SELECT Title FROM news")->result_array();
return ( is_array($query) && sizeof($query) > 0 ? $query : FALSE);
}
// example second
function get_all_pages_second() {
$data = FALSE;
$query = $this->db->query("SELECT Title FROM news");
if ($query->num_rows() > 0){
$data = $query->result_array();
}
return $data;
}
// example third
function get_all_pages_third() {
$data = FALSE;
$query = $this->db->select('Title')->get('news');
if ($query->num_rows() > 0){
$data = $query->result_array();
}
return $data;
}
}

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.

accessing array in array data pass from controller to view of 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;?>

Resources