How to fetch title of an item from a database and send it to the header template in CodeIgniter How to fetch title of an item from a database and send it to the header template in CodeIgniter codeigniter codeigniter

How to fetch title of an item from a database and send it to the header template in CodeIgniter


Try this

  1. Model is changed
  2. 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 


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>


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>