I am new to codeigniter and could be better at php. I have a news item being retrieved from the database table news, it has a foreign key of partner_id that is tied to the partners table. I want to get that value and use it to get the associated partner and display it's info. This is the latest of my attempts. I think I might be making it too hard. All relevant files are below. Thanks in advance.
In the model if the $id_partner is being assigned in the get_news function I don't think it is passing to the get_partner function.
news_model.php
public function get_news($slug_news = FALSE)
{
$this->load->helper('array');
if ($slug_news === FALSE)
{
$news_query = $this->db->get('news');
return $news_query->result_array();
}
$news_query = $this->db->get_where('news', array('slug' => $slug_news));
return $news_query->row_array();
global $id_partner;
$id_partner = element('partner_id', $news_query);
}
public function get_partner($id_partner = FALSE){
$partners_query = $this->db->get('partners');
$partners_query = $this->db->get_where('partners', array('id' => $id_partner));
return $partners_query->row_array();
}
The $slug_news in the view function doesn't apply to the partner part (obviously). but can I have another function?
controller, news.php
public function view($slug_news)
{
$data['news_item'] = $this->news_model->get_news($slug_news);
$partner_data['partner_listing'] = $this->news_model->get_partner($id_partner);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('news/news_partner', $partner_data);
$this->load->view('templates/sidebar');
$this->load->view('templates/footer');
}
view1, news/view.php
<?php
echo '<img src="/images/'.$news_item['thumb'].'" />';
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];
echo $news_item['bus_name'];
?><br>
and view2, news/news_partner.php
<?php
echo '<h2>'.$partner_listing['bus_name'].'</h2>';
echo $partner_listing['address1'];
echo $partner_listing['address2'];
echo $partner_listing['city'];
echo $partner_listing['state'];
echo $partner_listing['phone'];
echo $partner_listing['email'];
?>
Your model is a little all over the place. To start, the two lines after the return are never called in get_news. I would just simplify the model and do a simple join:
public function get_news()
{
$this->db->select('*');
$this->db->from('news');
$q = $this->db->join('partners', 'news.partner_id = partners.id');
return $q->result();
}
Here is what I put with your code:
public function get_news($slug_news = FALSE)
{
if ($slug_news === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$this->db->select('*');
$this->db->from('news');
$query_news = $this->db->join('partners', 'news.partner_id = partners.id');
return $query_news ->result();
}
I only used the "view.php" view as well. Does $slug_news need to be in there somewhere? How does it know what line to get? Thanks for your help, I am having so much trouble.
Related
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;
}
i have here:
public function index()
{
$this->is_logged_in();
$this->load->model('ReportModel');
$this->load->model('ConsultantModel');
if (isset($_POST['report'])){
$reports=$this->ReportModel->search($_POST['report']);
} else {
$reports=$this->ReportModel->get_last_ten_entries();
}
$models=$this->ReportModel->getModel();
$terms=$this->ReportModel->getTerm();
$username = $this->session->userdata('username');
$data['query'] = $this->ConsultantModel->getConsultantData($username);
//i want to send data to the report list view
//$this->load->view('report/reportlist', $data);
$this->load->view('report/reportlist', array('reports'=>$reports,'terms'=>$terms,'models'=>$models));
}
i want to pass both the array and the data in a single view (report/reportlist). i know that its possible because its very a simple idea but i don't know how. even if it can't, i know you guys know some tricks. please if you know, answer this.
public function index()
{
$this->is_logged_in();
$this->load->model('ReportModel');
$this->load->model('ConsultantModel');
$data = array();
if (isset($_POST['report'])){
$data['reports'] = $this->ReportModel->search($_POST['report']);
} else {
$data['reports'] = $this->ReportModel->get_last_ten_entries();
}
$data['models'] = $this->ReportModel->getModel();
$data['terms'] = $this->ReportModel->getTerm();
$username = $this->session->userdata('username');
$data['query'] = $this->ConsultantModel->getConsultantData($username);
$this->load->view('report/reportlist', $data);
}
You can use as following in your views -
1) Reports -
i) If single value -
echo $reports;
ii) If an array
foreach($reports as $report)
{
echo $report[..];
}
Similarly for rest.
I am trying to get data from a database and display it using a model, controller, and view.
Here is my model
public function waitlist_view() {
$data = array();
$this->load->database();
$this->db->select('*');
$this->db->from('waitlist');
$query = $this->db->get();
return $query->row();
}
Here is my controller
public function waitlist() {
$data['title']="parents_viewlist";
//redirect if not logged in
if(($this->session->userdata('logged_in')!= 1) && ($this->session->userdata('type')!='parent')) {
redirect('login/index');
}
$this->load->model('parents_model');
$data['row'] = $this->parents_model->waitlist_view();
$this->load->view('templates/cpsheader', $data);
$this->load->view('templates/cpsmenu');
$this->load->view('parents/parents_viewlist', $data);
$this->load->view('templates/cpsfooter');
}
Here is my view
<div>
<?php echo $row->waitlist_id; ?>
<?php echo $row->ay_code; ?>
<?php echo $row->school_id; ?>
<?php echo $row->waitlist_status; ?>
</div>
It doesnt display anything on the page when I pull it up. Any help would be appreciated!
in your model use result() to get data :
public function waitlist_view() {
$this->load->database();
$query = $this->db->get('waitlist')->result();
return $query;
}
in your controller :
$this->load->model('parents_model');
$data['row'] = $this->parents_model->waitlist_view();
$this->load->view('templates/cpsheader', $data);
$this->load->view('templates/cpsmenu');
$this->load->view('parents/parents_viewlist', $data);
$this->load->view('templates/cpsfooter');
Now use loop on $row in your view to print data.
In your controller print the data returned from db as:
echo "<pre>";print_r($data);echo "</pre>";exit;
add this line just after $data['row'] = $this->parents_model->waitlist_view();
Let us know what result are you getting.
It was hard to come up with a title. I am using CodeIgniter with models/views/controller. I have the following tables in my MySQL database that are relevant:
In my model I have the following function:
function get_shoptable() {
$this->db->from('productshop')->where('productId', $this->productId);
$query = $this->db->get();
return $query->result();
}
In my controller I use the above function like
$data['bookshop'] = $this->Product_model->get_shoptable();
In my view I am foreaching $bookshop. My problem is, what is the best wayto show shopName, instead of showing shopId. Taking in regards that $bookshop should be as it is (except of shopid), because I am creating a HTML table with product data.
Try some like this:
function get_shoptable() {
$this->db->from('productshop')
->join('shop', 'productshop.shopId = shop.shopId')
->where('productshop.productId', $this->productId);
$query = $this->db->get();
return $query->result();
}
Model:
function get_products() {
$this->db->select('productshop.productUrl, productshop.price, productshop.deliveryTime, productshop.shippingCast, productshop.inventory, productshop.productId, productshop.shopId, shop.shopName');
$this->db->from('productshop');
$this->db->join('shop', 'productshop.shopId = shop.shopId');
$this->db->where('productshop.productId', $this->productId);
return $this->db->get()->result_array();
}
Controller:
function products() {
$data['products'] = $this->model_name->get_product();
$this->load->view('products', $data);
}
VIEW:
<?php foreach($products as $p): ?>
<h1><?php echo $p['productUrl']; ?></h1>
<h1><?php echo $p['shopName']; ?></h1>
<?php endforeach(); ?>
get an overlook to active class of codeigniter for details of functions
function get_shoptable()
{
$this->db->from('productshop')
$this->db->join('shop', 'productshop.shopId = shop.shopId')
$this->db->where('productshop.productId', $this->productId);
$query = $this->db->get();
return $query->result();
}
i am doing some practice on the codeigniter to retrieve the data from database and i am success to do this.but the problem arise when i want to fetch data of a specific field.
to retrieve the specific value i am using the following URL on my local host:
localhost/codeigniter/index.php/news/view/city-news
where news is controller,view is method of controller and city-news is argument.
Here is my code of controller:
public function view($slug)
{
$data['news'] = $this->news_model->get_news($slug);//here i am getting the slug value.
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
this method calls the method get_news($slug) of model news_model.here is the code of this method:
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
echo $slug;//here is i m also getting the slug value.
$query = $this->db->get_where('news', array('slug' => $slug));//i think this is not working properly
print_r($query->row_array());die;//now i am getting values here.
return $query->row_array();
}
but still my view shows "404 page not found". my view code is:
<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];
?>
Now please tell me where i am going wrong.
your error is you are setting $data['news'] and testing $data['news_item'] :
$data['news'] = $this->news_model->get_news($slug);//here i am getting the slug value.
if (empty($data['news_item'])) // <=== HERE IS THE ERROR
{
show_404();
}
have you tried with simple where query as follows
$data = $this->db->where('slug', $slug)->from('news');
you must get something in $data. Means at least mysql object. Its been another part that whether rows are available in database or not.
secondly i am worried about the true and false. Means as per i know Boolean store as INT(1) means either 0 or 1. You needs to check with that as well.
you can debug your query with
$this->db->last_query();
Hope this helps.
Here is the cleaned code of the controller:
public function view($slug)
{
$news = $this->news_model->get_news($slug);
if (empty($news))
{
show_404();
}
$data['title'] =$news['title'];
$data['text'] = $news['text'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
this method calls the method get_news($slug) of model news_model:
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
echo $slug;
$query = $this->db->get_where('news', array('slug' => $slug));
print_r($query->row_array());die;//now i am getting values here.
return $query->row_array();
}
<?php echo '<h2>'.$title.'</h2>'; echo
$text; ?>
A small error:
Here
if (empty($data['news_item'])) // <=== put "news" here
{
show_404();
}
and at your view try to get data as
echo $news;
die() is a function use exit instead.
set this at the beginning of script
ini_set('display_errors', 1);
error_reporting(E_ALL);
also use var_dump($query); to check if it return any result if not exception or fatal error was raised when calling query
if array is empty it means that no news with this slug is in db. You should set some conditions when particular news is not found
also what is the value of this slug, does it contain any special chars etc.?