Skip to content
Advertisement

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

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?

Advertisement

Answer

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 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement