I don't know how to pass data from a class to one of my class to the studentShow template file.
MODEL
<?php
class Student{
public function all(){
require_once('config/db.php');
$SQLCommand = "SELECT * FROM people";
$Query = $conn->prepare($SQLCommand);
$Query->execute();
$rows = $Query->fetchAll(PDO::FETCH_OBJ);
return $rows;
}
}
?>
index
<?php
require_once("app/Controller/StudentController.php");
$Student = new StudentController();
$Student->index();
?>
Controller
<?php
require_once("app/Student.php");
class StudentController{
public function index(){
$Student = Student::all();
include ('resource/studentShow.php');
}
}
?>
My Question is: in my Controller how to pass that $student variable to studentShow.php.
Here is the way to achieve that:
public function index() {
$student = Student::all();
extract(['student' => $student]);
ob_start();
include ('resource/studentShow.php');
return ob_get_clean();
}
Read more about ob_start, extract & ob_get_clean
I am writing an application in CodeIgniter where I specify the <title> meta-tag on every page in every controller which I have managed to send to my header template. However, now I have created an application that fetch credit cards and their titles from the database, through an CodeIgniter model. I would like to automatically fetch and use the credit card's name in <title> so that i don't need to change it manually, but I'm a little stuck on how to proceed.
This is my code as of now:
Controller
public function show($card = NULL)
{
$data['query'] = $this->Listing_model->get_card($card);
$header["page_title"] = from the model
$this->load->view('includes/header',$header);
$this->load->view('listings/listing_card',$data);
$this->load->view('includes/footer');
}
Model
function get_card($card = FALSE)
{
$query = $this->db->get_where('creditcards', array('slug' => $card), 0,1);
return $query->result();
}
I have been following the official CodeIgniter documentation when creating this application, but so far no luck. Any solutions?
Try this
Model is changed
Controller is changed.
In Model
function get_card($card)
{
$query = $this->db->query("SELECT * FROM table_name WHERE creditcards = '$card' ");
$result = $query->result_array();
$count = count($result); # New
if(empty($count)){ # New
return FALSE;
}
elseif($count > 1){ # New
return 0;
}
else{
return $result;
}
}
In Controller
public function show($card)
{
$result = $this->Listing_model->get_card($card); # Changed
if($result == FALSE){ # New
echo "No Data Found";
}
elseif($result == 0){ # New
echo "Multiple Data Found";
}
else{
$data["page_title"] = $result[0]['field_name']; # Changed
$this->load->view('includes/header',$data); # Changed
$this->load->view('listings/listing_card',$data);
$this->load->view('includes/footer');
}
}
In View
<?php echo (!empty($page_title)) ? $page_title : ''; ?> # Changed
A simple example:
Controller
$query = $this->Listing_model->get_card($card);
$query = $query->row();
$header["page_title"] = $query->title;
View
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
You can create a Base Controller and Extends all you other controller to that base controller.
Like this
<?php
class MY_Controller extends CI_Controller {
public $data = array();
function __construct() {
parent::__construct();
$this->data['errors'] = array();
$this->data['site_name'] = config_item('site_name');
}
}
Then In Your Controller
class Test extends MY_Controller
{
function __construct() {
parent::__construct();
$this->data['meta_title'] = 'Your Title';
}
}
And in you views access the page title like this:
echo("<title>.$site_name.</title>");
Create a base controller. The default location for this is application/core/MY_Controller.php => this can be changed via the config.
By using $this->site_data you can add variables in your base class and use them in every controlle/view
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('your model');
$result = $this->Listing_model->get_card($card);
$this->site_data['query']=$result;
$this->site_data_header["page_title"] = $result['get the property you want'];//this is possible, as get_card returns 1 result
}
}
class YourClass extends MY_Controller
{
function __construct()
{
parent::__construct();
}
public function show($card = NULL)
{
//you don't need to split the variables
//for header and the rest
$this->load->view('includes/header',$this->site_data_header);
$this->load->view('listings/listing_card',$this->site_data);
$this->load->view('includes/footer');
}
}
And I think your get_where is wrong:
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
your limit is 0
function get_card($card = FALSE)
{
$query = $this->db->get_where('creditcards', array('slug' => $card), 1,0);//limit 1 offset 0
return $query->result();
}
access the data in your view
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
Controller
$card_data= $this->Listing_model->get_card($card); //Your model returns an array of objects
$header["page_title"] = $card_data[0]->title; //grab value of 'title' property of first object returned from model.
$this->load->view('includes/header',$header);
View
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
Try this:
function get_card($card = FALSE)
{
$data = $this->db->get_where('creditcards', array('slug' => $card), 0,1)->result();
$data->title = $data[0]->title;
return $data;
}
Controller
$query = $this->Listing_model->get_card($card);
var_dump($query);
//Your $query may be some data got from db;
$card_name = "";
if(!empty($query)){
$card_name = $query[0]->name; //You must verify the name attribute and it should in the $query result;
}
$header["page_title"] = $card_name;
View
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
You may need to create some routes for your show function. Codeigniter URI Routing
$route['your_controller_name/show/(:any)'] = 'your_controller_name/show/$1';
I am not sure if you have set up a htaccess for your main directory so you could remove the index.php from your url.
Try this code below
Model:
<?php
class Listing_model extends CI_Model {
function get_card_title($card) {
$this->db->where('slug', $card);
$query = $this->db->get($this->db->dbprefix . 'creditcards');
if ($query->num_rows() > 0) {
$row = $quer->row();
return $row->title;
} else {
return false;
}
}
}
Controller: Your_controller_name.php
<?php
class Your_controller_name extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('listing_model');
}
public function show($card) {
$data['title'] = $this->listing_model->get_card_title($card);
$this->load->view('includes/header', $data);
$this->load->view('listings/listing_card', $data);
$this->load->view('includes/footer');
}
}
View:
<head>
<title><?php echo $title;?></title>
</head>
In your listing card view, do this:
foreach ($query as $rec){
<title><?php echo $rec->title ?></title>
}
replace 'title' with the name of the column on your database that keeps the title of the credit card...so you are passing the results of the query you ran in your controller to this view, and then using a foreach loop to display data of the specific credit card
You can use template library for robustness and use as follows:
Controller
$this->template->title('Home :: ' . $this->data['metadata']['site_name'])
->set_layout('home_layout')
->build('listing_card', $this->data);
Views
<title><?php echo $template['title']; ?></title>
<?php echo $template['metadata']; ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Reference: https://github.com/philsturgeon/codeigniter-template
Just to add another, there's no reason this shouldn't work:
$data['query'] = $this->Listing_model->get_card($card);
$this->load->view('header', array('page_title' => $data['query'][0]->column_name));
//Will there only be one result? Consider returning $query->row(). Multiple,
//loop through and set one title
In your view:
<title><?=isset($page_title) ? $page_title : "";?></title>
If this doesn't work your query isn't returning what you think it is.
Controller :
$data["page_title"] = $result[0]['title_field'];
view:
and You just need to write in your header file like :
<title><?php echo $page_title; ?></title>
In your model - don't return $query->result(), just return $query:
function get_card($card = FALSE)
{
$query = $this->db->get_where('creditcards', array('slug' => $card), 0,1);
return $query;
}
Controller:
public function show($card = NULL)
{
// verify that you got something back from the database
// or show an error
if( ! $query = $this->Listing_model->get_card($card) )
{
$this->_showNoResultsFor($card) ;
}
else
{
// get one record from the query using row()
$onecard = $query->row() ;
// assign the title using whatever your field name is called
$header["page_title"] = $onecard->thetitle ;
// Now assign the query result() to data
$data['query'] = $query->result() ;
$this->load->view('includes/header',$header);
$this->load->view('listings/listing_card',$data);
$this->load->view('includes/footer');
}
}
I call the parent constructor as I extend new controllers from CI_Controller and MY_Controller so that I can enjoy higher variable declarations that are shared throughout the project.
I recommend creating general use model methods so that they have greater utility and can be re-used by many controllers in your project.
To make it easier to load header data into all controllers in your project, I recommend declaring some default header data in MY_Controller then within lower level controllers, you can amend that data and pass it to the view(s).
ci/application/core/MY_Controller.php
<?php
/**
* #property Listing_model ListingModel
* #property CI_DB_query_builder|CI_DB_postgre_driver $db
* #property CI_Loader $load
* #property CI_Config $config
*/
class MY_Controller extends CI_Controller
{
protected $headerData;
public function __construct()
{
parent::__construct();
$this->headerData['title'] = 'Some Default Title';
$this->headerData['js'] = [
'loaded_unconditionally.js',
];
$this->headerData['css'] = [
'loaded_unconditionally1.css',
'loaded_unconditionally2.css',
];
}
}
ci/application/controllers/Listing.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Listings extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Listings_model', 'ListingsModel');
}
public function show(string $card): void
{
$listing = $this->ListingModel->getByCard($card);
$this->headerData['title'] = $listing->name ?? 'Invalid Card Provided';
$this->load->view('layout/header', $this->headerData);
$this->load->view('listings/listing_card', ['listing' => $listing]);
$this->load->view('layout/footer');
}
}
ci/application/models/Listings_model.php
// returns object or null
function getByCard(string $card): ?object
{
// it is assumed that the slug column will be UNIQUE
return $this->db->get_where('creditcards', ['slug' => $card])->row();
}
// returns empty array or array of objects
function get(?int $limit, int $offset = 0): array
{
$args = ['creditcards'];
if ($limit !== null) {
array_push($args, $limit, $offset);
}
return $this->db->get_where(...$args)->result();
}
ci/application/views/layout/header.php
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $title; ?></title>
<?php foreach ($css as $filepath) { ?>
<link rel="stylesheet" href="<?php echo base_url("assets/css/$filepath"); ?>" />
<?php } ?>
<?php foreach ($js as $filepath) { ?>
<script src="<?php echo base_url("assets/js/$filepath"); ?>" />
<?php } ?>
</head>
ci/application/views/listings/listing_card.php
<?php
/**
* #var object|null $listing
*/
// start crafting your html markup and reference $listing as needed
if (!empty($listing->name)) {
echo "<p>Hello $listing->name</p>";
} else {
echo "<p>Um, who are you again?</p>";
}
I have two functions in my model as
class Jobseeker_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function result_getall($id)
{
$this->db->select('*');
$this->db->from('tbl_jobseeker');
$this->db->where('tbl_jobseeker.User_id',$id);
$this->db->join('tbl_work_exp', 'tbl_jobseeker.User_id = tbl_work_exp.User_id','left');
$query = $this->db->get();
return $query->row();
}
public function select($id)
{
$this->db->select('*');
$this->db->from('tbl_qualification');
$this->db->where('tbl_qualification.User_id',$id);
$query = $this->db->get();
return $query->result();
}
}
And in my controller I have a function as
public function display()
{
$id = $this->session->userdata('user_id');
$data['row'] = $this->jobseeker_model->result_getall($id);
$res['a'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data,$res);
}
It is not possible to display the view page.. I could pass two variables into my view page.right?
You can pass your any number of variables/arrays using a single array.
In Controller:
public function display() {
$id = $this->session->userdata('user_id');
$data['var1'] = $this->jobseeker_model->result_getall($id);
$data['var2'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data);
}
In View:
`$var1` and `$var2` will be available.
You can pass your two variable using single srray
public function display()
{
$id = $this->session->userdata('user_id');
$data['row'] = $this->jobseeker_model->result_getall($id);
$data['a'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data);
}
Views
foreach($a as $data){
// your code
}
echo $row->column_name;
Try this
public function display()
{
$id = $this->session->userdata('user_id');
$data['row'] = $this->jobseeker_model->result_getall($id);
$data['a'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data);
}
I have a template that loads my view into parts like header, footer and main_content. I have a widget in the footer where i would like to display top 5 posts of a particular category, say "Current Affairs". Since the template is loaded in parts, i want a function that loads this data and provide it to the footer.php file of the template. However, this function should be loaded in the constructor so that all the other functions of the controller doesnt need to call this function. Heres my code.
class Home extends CI_Controller {
// public $data['latest_current_affairs'] = array(); // Tried this, doesnt work.
function __construct()
{
parent::__construct();
$this->load->model('Add');
$this->load->model('Fetch');
$this->load->library('form_validation');
$this->load->helper('date');
// $this->load_widgets(); //works fine if we print an array
}
public function load_widgets()
{
$where = array('post_category' => "Current Affairs", 'post_status' => "Published");
$orderby = NULL;
$limit = 5;
$data['latest_current_affairs'] = $this->Fetch->selectWhereLimit('post', $where, $orderby, $limit);
// print_r($data); //works fine if printed through here.
}
public function index()
{
$data['main_content'] = 'home';
$this->load_widgets();
$this->load->view('includes/template', $data);
print_r($data); //Here the data prints only the main_content index but not the latest_current_affairs index of the array.
}}
Here's the content of my template.php:
<?php $this->load->view('includes/header'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer'); ?>
Any suggestions for code optimization or better coding techniques are welcome.
Here is the sample Code To store data in global array.
class Check extends CI_Controller
{
public function __construct() {
parent::__construct();
$this->data['f1'] = $this->f1();
}
function f1()
{
return "response1";
}
function f2()
{
$this->data['f2'] = "response2";
print_r($this->data);
}
}
To declare globe array in codeigniter you have to define in your config file
$config['item_name']= array('post_category' => "Current Affairs", 'post_status' => "Published");
For fetching config item
$this->config->item('item_name');
So your index function would be
public function index()
{
$where=$this->config->item('item_name');
$orderby = NULL;
$limit = 5;
$data['latest_current_affairs'] = $this->Fetch->selectWhereLimit('post', $where, $orderby, $limit);
$data['main_content'] = 'home';
$this->load->view('includes/template', $data);
print_r($data); //Here the data prints only the main_content index but not the latest_current_affairs index of the array.
}
UPDATED
You can create helper file for it
function load_widgets()
{
$CI = get_instance();
$CI->load->model('Fetch');
$where=$CI->config->item('item_name');
$orderby = NULL;
$limit = 5;
return $latest_current_affairs = $CI->Fetch->selectWhereLimit('post', $where, $orderby, $limit);
}
And you Controller
function __construct()
{
parent::__construct();
$this->load->model('Add');
$this->load->model('Fetch');
$this->load->library('form_validation');
$this->load->helper('date');
$result=$this->load_widgets();
print_r($result);
}
ans don't forget to call your helper file
Here is my code.
public function usertype($renderData='')
{
$this->grocery_crud->set_table('usertype');
$output = $this->grocery_crud->render();
$this->_example_output($output,$renderData='');
}
function _example_output($output = null,$renderData='')
{
// $this->load->view('pages/our_template',$output);
//echo $output;
// $this->output=$output;
$this->_render('pages/our_template',$renderData);
}
I want to use $this->_render('pages/our_template',$renderData); instead of $this->load->view('pages/our_template',$output); But I need to pass $output to the view page. Please help me to find a way to pass $output to my view page using $renderData.
And in my view page I want to get the the data
like
echo $output;
hi you can to do with view like this
$output = $this->load->view('pages/our_template',$data,TRUE); // this will return view output to variable
echo $output
Edited New Answer
First of all sorry for wrong answer
if you want to use $this->_render method then you have to take advantage of OOP create a MY_Controller under application/core directory and add _render method in it, extends your all controllers with MY_Controller like this
class MY_Controller extends CI_Controller{
function __construct(){
parent::__construct();
}
function _render($view = '', $data = array(), $return = FALSE){
if($return){
return $this->load->view($view,$data,$return);
}
$this->load->view($view,$data);
}
}
Example Page Controller
class PageController extends MY_Controller{
function __construct(){
parent::__construct();
}
function index(){
$data['title'] = 'Page title';
$data['body'] = 'Page body';
$this->_render('page_view',$data);
}
}
if you are using a layout for your project which has header,footer, sidebars then you can make render method little bit advance
function _render($view = '', $data = array(), $return = FALSE){
$output = $this->load->view($view,$data,TRUE);
if($return){
return $output;
}
$layout_data['header'] = $this->load->view('header_view',$data,TRUE);
$layout_data['footer'] = $this->load->view('footer_view',$data,TRUE);
$layout_data['sidebar'] = $this->load->view('sidebar_view',$data,TRUE);
$layout_data['body'] = $output;
$this->load->view('layout',$layout_data);
}
if you like answer accept and up it.