codeigniter join query, display data to view - php

im new to codeigniter & php, and i have some question about join() function.
i have this model:
public function get_categorie()
{
$this->db->select('*');
$this->db->from('foxCategory');
$this->db->join('foxAnnunci', 'foxCategory.id = foxAnnunci.id_foxCategory');
$query = $this->db->get();
}
this controller:
public function index()
{
$data['category']= $this->annunci_model->get_categorie();
$data['annunci'] = $this->annunci_model->get_annunci();
$data['titolo'] = 'Elenco annunci';
$this->load->view('templates/header', $data);
$this->load->view('annunci/index', $data);
$this->load->view('templates/footer');
}
and this view
<h2><?php echo $value['titolo'] ?></h2>
<div id="main">
<code>Data di creazione: <?php echo $value['creato_il'] ?></code><br />
<?php echo $value['descrizione'] ?>
</div>
<p>Guarda annuncio || <p><?php echo $category['category']['titolo'] ?></p></p>
i want to display the name of category as link (classic for blog category function), but this code show nothing, what is the problem?

Related

Codeigniter admin users dashboard issue

Actually, i'm working on Codeigniter admin dashboard users module,i'm trying to show (dashboard) how many users is there from user table from database enter image description here
model file code:
function usercount_total($userId)
{
$this->db->select('count(1)');
$this->db->from('tbl_users');
$query = $this->db->get();
return $query->result();
}
controller file:
$res['total_users'] = $this->user_model->usercount_total($userId);
$this->loadViews("dashboard", $this->global, $res, NULL);
view file:dashboard.php
<div class="inner">
<!-- <h3>44</h3> -->
<h3><?php echo $total_users; ?></h3>
<p>New User</p>
</div>
You can do it with the help of helpers (an alternative)
Add a file name custom_helper.php in helpers folder and load it with the help of autoload.php like this;
$autoload['helper'] = array('custom');
In custom_helper.php add a method called users_count() like this :
function users_count()
{
$ci = & get_instance();
return $ci->db->count_all('tbl_users');
}
In view do like this :
<div class="inner">
<h3><?php echo users_count(); ?></h3>
<p>New User</p>
</div>
For more :https://www.codeigniter.com/user_guide/general/helpers.html
Use $this
function usercount_total($userId)
{
$this->db->select('count(*)');
$this->db->from('tbl_users');
$query = $this->db->get();
return $query->num_rows();
}

I can't get CodeIgniter posts with specific categories to show on home page (I will delete this if it turns out to be a duplicate)

I am looking for suggestions, I searched the questions on here and did not find anything that matched what I was asking. That being said if you feel this is a duplicate I will gladly remove the question, and hopefully get the link to the OP.
I am new to CodeIgniter and I have built out the blog portion of a website (auth, post index, create posts and categories, and comments) on top of that I have the db setup to attach the category_id to each new post.
My issue is that I can list the categories and even link them to an index filtered to just post with that category name but I am trying to list posts categorized as featured articles on the home page of the website So once you visit the website latest featured articles can be displayed with a read more.
Below is all the code for making the categories show in list form on the view/categories/index.php and views/posts/index.php. I thought I could use the get_posts_by_category to display outside of the categories index page but I get this error
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: categories
Filename: pages/home.php
The Index portion of the Posts.php Controller
public function index($offset = 0){
// Pagination Config
$config['base_url'] = base_url() . 'posts/index/';
$config['total_rows'] = $this->db->count_all('posts');
$config['per_page'] = 3;
$config['uri_segment'] = 3;
$config['attributes'] = array('class' => 'pagination-link');
// Init Pagination
$this->pagination->initialize($config);
$data['title'] = 'Latest Posts';
$data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);
$this->load->view('templates/header');
$this->load->view('posts/index', $data);
$this->load->view('templates/footer');
}
get_posts port of the Post_model.php
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE) {
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE) {
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.category_id');
$query = $this->db->get('posts');
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->row_array();
}
get_categories and get_posts_by_category portion of the Post_model.php
public function get_categories() {
$this->db->order_by('name');
$query = $this->db->get('categories');
return $query->result_array();
}
public function get_posts_by_category($category_id) {
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.category_id');
$query = $this->db->get_where('posts', array('category_id' => $category_id));
return $query->result_array();
}
** View portion of the categories/index.php**
<h2><?= $title; ?></h2>
<ul class="list-group">
<?php foreach($categories as $category) : ?>
<li class="list-group-item">
<?php echo $category['name']; ?>
<!-- user data -->
<?php if($this->session->userdata('user_id') == $category['user_id']): ?>
<form class="cat-delete" action="categories/delete/<?php echo $category['id']; ?>" method="POST">
<input type="submit" class="btn-link text-danger" value="[X]">
</form>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
Categories Controller - index an posts function
public function index(){
$data['title'] = 'Categories';
$data['categories'] = $this->category_model->get_categories();
$this->load->view('templates/header');
$this->load->view('categories/index', $data);
$this->load->view('templates/footer');
}
public function posts($id){
$data['title'] = $this->category_model->get_category($id)->name;
$data['posts'] = $this->post_model->get_posts_by_category($id);
$this->load->view('templates/header');
$this->load->view('posts/index', $data);
$this->load->view('templates/footer');
}
Below is of the MySQL db table for posts (figured I can call the category_id)
id
category_id
title
slug
body
post_image
created_at
This error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: categories
Filename: pages/home.php
Implies that your view (home.php) is attempting to use a variable (categories) that is not defined, i.e. not passed in by the controller.
You ARE correctly passing the variable to a view called "index", here:
$data['categories'] = $this->category_model->get_categories();
$this->load->view('categories/index', $data);
But not "home"... where are you loading "home"? Where ever that is, you would need to pass the data to it in the same fashion as above.

Displaying the page titles based on the pages dynamically in codeigniter php

How to display page titles dynamically based on the pages displayed.
Hi i am having a site developed in codeigniter php but the problem is need to display page titles dynamically based on the pages.These pages titles should be fetched from database.Can anyone have any idea how to do this.
Controller:
public function index()
{
$config = array();
$config["base_url"] = base_url('testimonial/index');
$config['total_rows'] = $this->testimonial_model->record_count();//here we will count all the data from the table
$config['per_page'] = 6;//number of data to be shown on single page
$config['first_link'] = 'First';
$config['last_link'] = 'Last';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["records2"] = $this->testimonial_model->get_all_testimonials($config["per_page"], $page);
$data['records7'] = $this->index_model->get_all_banners();
$data["links"] = $this->pagination->create_links();//create the link for pagination
$data['mainpage'] = "testimonial";
$this->load->view('templates/template',$data);
}
Model:
function get_all_testimonials($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->select('T.*');
$this->db->from('testimonials AS T');
$this->db->where(array('T.status'=>1));
$q = $this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div class="container">
<div class="row testimonialpage">
<div class="col-md-12 testimonialpage">
<div class="col-md-9 testimonials" >
<div class="testimonialpagetext">
</div>
<?php if(isset($records2) && is_array($records2)):?>
<?php foreach ($records2 as $r):?>
<div class="testimonial1">
<div class="testimonialtext1">
<?php echo $r->description;?>
<ul class="founders">
<li class="founder"><?php echo $r->client_name;?></li>
<li class="founder"><?php echo $r->founder;?></li>
</ul>
</div>
</div>
<?php endforeach ;endif;?>
<div class="pagination"><?php echo $links; ?></div>
</div>
</div>
</div>
For Ex:: Your url is www.example.com/controller/register when you get uri segment(2) means you will get (register). based on this you can identify that you are on the register page. now you can find the title for register page from your database.
Every time i build an application with Codeigniter, i use a Class MY_Controller that extends CI_Controller, inside application/core like bellow:
class MY_Controller extends CI_Controller {
protected $view_data;
function __construct() {
//......
}
}
Any controller inside application/controllers will extend the MY_Controller instead of CI_Controller.
Now in the constructor of MY_Controller you can do something like:
$page = $this->uri->segment(2); (2 or 3 or 4 etc, depends on your structure)
Load your model, execute your query and add the result in $this->view_data like:
$pageTitle = $this->your_model->getPageTitle($page);
$this->view_data['page_title'] = $pageTitle['page_title'];
Example of getPageTitle in your model:
public function getPageTitle($page) {
$qry = $this->db->select('page_title')
->from('pages')
->where('page', $page)
->get();
if ($qry->num_rows() > 0)
return $qry->row_array();
return false;
}
Watch out the sample names i gave, you should change those!
To load your view, pass the variable $this->view_data as parameter and in your view do something like
<title><?= $page_title ?></title>

CodeIgniter pass variable from controller to view

Sorry if this question is already been answered, but i couldn't find an answer.
I want to pass a variable from my model to the controller and finally display it in the view.
I execute a query on the database and after that I count my results (via num_rows). Then I return the result.
public function countHighRisk(){
$this->db->select("ares_status");
$this->db->from("tbl_alert_result");
$this->db->join('tbl_status_standards', 'ares_status = sts_status_id');
$this->db->where('sts_status_risk', 3);
$query = $this->db->get();
return $query->num_rows();
}
After that i place the result in an array and pass the array to my view.
public function index()
{
$this->load->model('Alert_result_model');
$data['high'] = $this->Alert_result_model->countHighRisk();
$this->load->view('templates/head');
$this->load->view('templates/menu');
$this->load->view('pages/Dashboard', $data);
$this->load->view('templates/footer');
}
I get an error when I try to display the variable in the view.
<div class="col-xs-8 text-right">
<span> High Risk </span>
<h2 class="font-bold"><span class="count"><?= $high; ?></span></h2>
</div>
error: http://imgur.com/iHkYHiI
Thanks in advance.
Your whole idea of calling the views is wrong here. Please use it as follows:
Controller:
public function index()
{
$this->load->model('Alert_result_model');
$data['high'] = $this->Alert_result_model->countHighRisk();
$this->load->view('pages/Dashboard', $data);
}
View:
<? $this->load->view('templates/head'); ?>
<? $this->load->view('templates/menu'); ?>
<div class="col-xs-8 text-right">
<span> High Risk </span>
<h2 class="font-bold"><span class="count"><?= $high; ?></span></h2>
</div>
<? $this->load->view('templates/footer'); ?>
Also check what $this->Alert_result_model->countHighRisk(); is actually returning by doing print_r($this->Alert_result_model->countHighRisk();)
You can load a view into controller but do this way below
class Dashboard extends CI_Controller {
public function index() {
$this->load->model('Alert_result_model');
$data['high'] = $this->Alert_result_model->countHighRisk();
// Choose only one header examples:
$data['header'] = $this->load->view('header', Null, TRUE); // If No Data
$data['header'] = $this->load->view('header', $data, TRUE); // If Data
// Choose only one Footer examples:
$data['footer'] = $this->load->view('footer', Null, TRUE); // If No Data
$data['footer'] = $this->load->view('footer', $data, TRUE); // If Data
$this->load->view('dashboard', $data);
}
}
Dashboard View
<?php echo $header;?>
<?php foreach ($high as $low) { ?>
<?php echo $low['something'];?>
<?php }?>
<?php echo $footer;?>
If you have a header separate header controller and footer controller you will need HMVC if you are confused on user guide top right corner of default user guide in CI3 is a switch to more cleaner version.
please change
$this->load->view('pages/Dashboard', $data);
into
$this->load->view('pages/Dashboard', $data, true);
now it should work.

FuelPHP basics, using Model result in View

I am a little confused using fuelPHP 1.7.
The controller
class Controller_Website extends Controller
{
public function action_index()
{
// http://fuelphp.com/docs/general/views.html
$data = Website::get_results();
//var_dump($data) // (data is found here);
$views = array();
$views['head'] = View::forge('common/head', $data);
$views['header'] = View::forge('common/header', $data);
$views['sidebar'] = View::forge('common/sidebar', $data);
$views['content'] = View::forge('common/content', $data);
$views['footer'] = View::forge('common/footer', $data);
// return the rendered HTML to the Request
return View::forge('website', $views)->render();
}
}
The model
class Website extends \Model
{
public static function get_results()
{
// Database interactions
$result = DB::select('menu', 'url', 'title', 'text')
->from('aaa_website')
->where('id', '=', 1035)
->and_where('visible', '1')
->execute();
return $result;
}
}
All well sofar. Data is queried and found in the controller. What I am trying to accomplish is to use the data in my:
(nested) view
<html>
<head>
<?php echo $head; ?>
</head>
<body>
<header>
<div class="container">
<?php echo $header; ?>
</div>
</header>
<div class="row">
<div class="container">
<div class="col-md-4">
<?php echo $sidebar; ?>
</div>
<div class="col-md-8">
<?php echo $content; ?>
</div>
</div>
</div>
<footer>
<div class="container">
<?php echo $footer; ?>
</div>
</footer>
</body>
</html>
Head view (nested):
<title><?php echo $title; ?></title>
Content view (nested):
<h1><?php echo $title; ?></h1>
<div class="welcome_user"><?php echo $text; ?></div>
And so on.
The variables in the view in this example are not available because they are not explicitly set in the controller. Do they have to be set explicitly or is passing the data object also possible? If so, how do I access this objects data in the right way? FuelPHP is lacking good examples here and I am stuck now.
How do I do it?
The view data is converted from array indexed to view variable named. So:
View::forge('something', array('param' => 'value'));
Will correspond to the following view:
<h1><?=$param?></h1>
Where things are going wrong is is that you pass the plain DB result to the view. You'd need to get the first result from the database result, like this:
class Website extends \Model
{
public static function get_results()
{
// Database interactions
$result = DB::select('menu', 'url', 'title', 'text')
->from('aaa_website')
->where('id', '=', 1035)
->and_where('visible', '1')
->as_assoc()
->execute()
->to_array();
return reset($result);
}
}
Note that I've first used ->to_array() to convert the result object to an array, then reset() to get the first result. I've also added ->as_assoc() to make sure you get an array result, ->as_object() would give you a stdClass instance.

Categories