I need to call a controller function inside a view -Codeigniter - php

I need to call a function from view to echo a value. I use following code,
Controller (test_controller)
public function displayCategory()
{
$this->load->model('Model_test');
$data['categories'] = $this->Model_test->getCategories();
$this->load->view('test_view', $data);
}
public function display($id)
{
$this->load->model('Model_test');
$name= $this->Model_test->getName($id);
return $name;
}
Model (Model_test)
function getCategories() {
$query = $this->db->query("SELECT * FROM category");
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
function getName($userId) {
$query = $this->db->query("SELECT name FROM user where id = '$userId' ");
if ($query->num_rows() > 0) {
return $query->row()->name;
} else {
return NULL;
}
}
View
<div id="body">
<?php
foreach ($categories as $object) {
$temp = $this->test_controller->display($object->id);
echo $object->title . " ". $object->no . $temp . '<br/>';
}
?>
</div>
but some error when running the code.
error Message: Undefined property: CI_Loader::$test_controller in view

I am not sure if you use CodeIgniter 2 or 3.
Anyway, basically you don't want to use anything inside View files except perhaps helper function(s) or some kind of "presenter" layer (that should be called inside controller I guess).
Solution using Join
Go and read this manual page and search for join. There you can learn about implementation of SQL join directive.
You want to modify this (getCategories()) function so it returns data that you require
function getCategories() {
$this->db->select('category.title, category.no, user.name as username')
->from('category')
->join('user', 'user.id = category.id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
and in view you can get your username like this
foreach ($categories as $object) {
echo $object->title . " ". $object->no . $object->username . '<br/>';
}
I am not 100% sure so please post comments I will edit this answer later.
Solution "breaking rules"
https://stackoverflow.com/a/24320884/1564365
general notes
Also consider naming your tables using plural so categories, users...
Also it is a bad practise to use "category.id as user.id" (storing user id inside category table in "id" field) instead you shold use either a pivot table or in case of 1:1 relation field "user_id".

Related

Fetch data from database in codeigniter

I have 2 cases where i am fetching the entire data and total number of rows of a same table in codeigniter, I wish to know that is there a way through which i can fetch total number of rows, entire data and 3 latest inserted records from the same table through one code
Controller code for both cases is as given below (although i am applying it for each case seperately with different parameters)
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$data);
}
1) to fetch the entire data from a table in codeigniter
Model Code
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->result();
}
View Code
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
2) to fetch number of rows from a table in codeigniter
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->num_rows();
}
View Code
echo $instant_req;
You can make only one function that gives you the all data at once total number of rows, entire data and 3 latest inserted records
for example in the model
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$result=$query->result();
$num_rows=$query->num_rows();
$last_three_record=array_slice($result,-3,3,true);
return array("all_data"=>$result,"num_rows"=>$num_rows,"last_three"=>$last_three_record);
}
in controller dashboard function
public function dashboard()
{
$result = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$result);
}
in view
foreach ($all_data as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//latest three record
foreach ($last_three as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//total count
echo $num_rows;
Raw query may work here.
$resultSet = $this->db->query("select * from table_name");
$queryCount = count($resultSet );
Try this logic :
Model code :
public function getreq()
{
$this->db->where('status','pending');
$this->db->order_by('id', 'DESC'); //actual field name of id
$query=$this->db->get('instanthire');
return $query->result();
}
Controller Code :
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$data['total_record'] = count($data['instant_req']);
$this->load->view('admin/dashboard',$data);
}
View Code:
$i=0;
foreach ($instant_req as $perreq)
{
if($i<3){
echo $perreq->fullname;
echo "<br>";
}
$i++;
}
Echo 'Total record : '.$total_record;
Function
function getData($limit = 0){
//Create empty array
$data = [];
//Where clause
$this->db->where('status','pending');
//Order Data based on latest ID
$this->db->order_by('id', 'DESC');
if($limit != 0){
$this->db->limit($limit);
}
//Get the Data
$query = $this->db->get('instanthire');
$data['count'] = $query->num_rows();
$data['result'] = $query->result();
return $data;
}
Calls
//Last 3 Inserted
$data = getData(3);
//All Data
$data = getData();
CodeIgniter Database Documentation
Here is a simple solution that I can first think of but if you want me to maybe improve I can.
Just stick with your first code(Model) and in the view count how many items are iterated through.
$count = 0;
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
$count++;
}
echo $count;
Am I still missing something? just let me know
EDIT:
This is another solution, return an array
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$data['results'] = $query->result();
$data['count'] = $query->num_rows();
return $data
}
I'm not very confident and haven't really tried this but on top of my head I think it can work.
Model:
public function getreq()
{
$res = $this->db->order_by("<place column primary id>","desc")->get_where('instanthire',['status'=> 'pending']);
$latest_3 = [];
if(count($res)){
$i=1;
foreach($res as $r){
$latest_3[]=$r;
if($i == 3)
break;
$i++;
}
}
$arr = [
'latest_3' => $latest_3,
'count' => count($res),
'total_result' => $res,
];
return $arr;
}

How to access multiple values to code igniter view

Passing multiple values as an array is working. But when i want access the variable only 1st array variable can access.
I think the problem comes from model. when i used $this->db->select('*'); no issue occur. Why it happen? Then how to access other variable.
Controller
public function index() {
$this->load->model('prop_model');
$pro_data['pro'] = $this->prop_model->get_data_all();
$this->load->view('home/main_view', $pro_data);
}
Model (prop_model)
function get_data_all() {
$this->db->select('prop_id', 'content', 'added_date');
$query = $this->db->get('tble_prol');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
view
<div class="col-md-9">
<?php
foreach ($pro as $add) {
echo '<div class="grid-item well"><p>'
. $add->content .'<br>' . $add->added_date //error here when access added_date
. '</p></div>';
}
?>
</div>
Try this:
$this->db->select('prop_id,content,added_date');
The query syntax is wrong. See for the reference: ActiveRecordsSyntax

How To Fetch And Display Multiple Rows?

I'm using Magento which is on the zend framework and the following code currently outputs the first row matching the criteria is_read != 1', 'is_remove != 1'. I need to modify this code to output the last 4 table rows that matches said criteria. I tried a few things but none worked. Please Help!
ModuleName/Model/Resource/
public function loadLatestNotice(Mage_AdminNotification_Model_Inbox $object)
{
$adapter = $this->_getReadAdapter();
$select = $adapter->select()
->from($this->getMainTable())
->order($this->getIdFieldName() . ' DESC')
->where('is_read != 1')
->where('is_remove != 1')
->limit(1);
$data = $adapter->fetchRow($select);
if ($data) {
$object->setData($data);
}
$this->_afterLoad($object);
return $this;
}
Here are some other codes that are used...
ModuleName/Model/
public function loadLatestNotice()
{
$this->setData(array());
$this->getResource()->loadLatestNotice($this);
return $this;
}
ModuleName/Block/
public function getLatestNotice()
{
return $this->_getHelper()
->getLatestNotice()->getTitle();
}
Template/
href="<?php echo $latestNoticeUrl ?>" onclick="this.target='_blank';"><?php echo $this->getLatestNotice() ?>
I was able to solve the problem myself, by using the following method.
The first thing i tried to produce is 4 notification table rows instead of 1, is to change ->limit(1); to ->limit(4); and $adapter->fetchRow($select); to $adapter->fetchAll($select);. The issue is, the solution requires more than just changing these 2 values.
ModuleName/Model/Resource/
public function loadLatestNotice(Mage_AdminNotification_Model_Inbox $object)
{
$adapter = $this->_getReadAdapter();
$select = $adapter->select()
->from($this->getMainTable())
->order($this->getIdFieldName() . ' DESC')
->where('is_read != 1')
->where('is_remove != 1')
->limit(4);
$data = $adapter->fetchAll($select);
if ($data) {
$object->setData($data);
}
$this->_afterLoad($object);
return $this;
}
After changing this, the template will stop outputting information, In order for the template to output the new array, you must duplicate some code and remove ->getTitle() line in the block file, then change a few line of codes in the template .phtml file as follows.
ModuleName/Block/
public function getNewFuncName()
{
return $this->_getHelper()
->getLatestNotice();
}
Template/
<?php
$notice = $this->getNewFuncName();
foreach ($notice as $item) {
foreach ($item as $value) {
echo '<div class="notemssg"><p id="notetitle" href='.$value['url'].' >'.$value['title'].'</p><p id="notedate">'.$value['date_added'].'</p></div>';
}
}
?>
Changing the code to properly call and display the array will result it 4 table rows being displayed. the code can be modified to be used and any way you would like to display the info on the fronted.
Hope this helps Someone!

Check if category has parent

i'm in mid of creating my own cms . And now i want to show which one of the category has parent but i don't know how, so please help me.
my category table
idkategori | namakategori | parentid
1 Programming 0
2 PHP 1
Or i need relationship table for my categories?
My Controller so far.
function tampilmenu()
{
$sql = "select * from fc_kategori";
$data['kategori'] = $this->bymodel->tampildata($sql);
$sql1 = "select parentid from fc_kategori";
$data['parent'] = $this->bymodel->tampildata($sql1);
$id=array();
foreach ($data['parent'] as $paren)
{
$id[]=$paren->parentid;
}
foreach ($data['kategori'] as $cat)
if(in_array($cat->parentid,$id))
{
$have ='Yes';
}
else
{
$have ='No';
}
echo $cat->idkategori.$have;
}
}
my model
function tampildata ($sql)
{
$query = $this->db->query($sql);
return $query->result();
}
Please don't laugh on me.
Kindly follow:
1) Since you are using a MVC framework, never write queries inside the controller (queries should always be written in models).
2) Never use raw queries, since CI provides you what is called as Active Record.
3) Also never pass direct queries anywhere you'll possibly code in whichever language. Always pass data and make do that function to compute and query process.
4) Remember, in CI Models are only used for database functionalities, Views are only used for your HTML markups and Controllers acts as the mediator between models and views.
Your code:
Controller -
public function tampilmenu()
{
$categories = $this->bymodel->get_category_having_parent();
echo "<pre>"; print_r($categories);
// this will return object having all categories that are parents
}
Model -
public function get_category_having_parent()
{
$parent_ids = array();
$ps = $this->get("parentid");
foreach($ps as $p)
{
$parent_ids[] = $p->parentid;
}
$this->db->where_in("id", $parent_ids);
$query = $this->db->get("fc_kategori");
return $query->result();
}
public function get($column="*")
{
$this->db->select($column);
$query = $this->db->get("fc_kategori");
return $query->result();
}

Join does not work

I have write a function using SQL join but i do not know why it does not work
this is a model
public function get_contract_user($user_id)
{
$this->db->select('contracts.*');
$this->db->from('contracts');
$this->db->join('link', 'contracts.contract_id = link.contracts_contract_id');
$this->db->where('link.users_user_id', $user_id);
$query = $this->db->get();
return $query->result();
}
this is the app
$data['query'] = $this->admin_model->get_contract_user($contract_id);
this is a view
foreach($query as $row)
{
echo $row->contract_code;
echo $row->contract_num;
echo $row->contract_start;
echo $row->contract_end;
}
You defined method get_contract_user, but you are using get_contract in provided code.
You should be getting an error concerning undefined function/method.

Categories