如何从数据库中获取项目的标题并将其发送到 CodeIgniter 中的 header 模板

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

我正在 CodeIgniter 中编写一个应用程序,我在每个控制器的每个页面上指定了 <title> meta-tag,我已设法将其发送到我的 header 模板。但是,现在我已经创建了一个应用程序,它通过 CodeIgniter 模型从数据库中获取信用卡及其名称。我想在 <title> 中自动获取和使用信用卡名称,这样我就不需要手动更改它,但我对如何进行有点困惑。

这是我目前的代码:

控制器

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');
}

型号

function get_card($card = FALSE)
{
    $query = $this->db->get_where('creditcards', array('slug' => $card), 0,1);
    return $query->result();
}

我在创建这个应用程序时一直在关注官方 CodeIgniter 文档,但到目前为止还没有成功。有什么解决办法吗?

一个简单的例子:

控制器

$query = $this->Listing_model->get_card($card);
$query = $query->row();

$header["page_title"] = $query->title;

查看

<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>

在您的列表卡片视图中,执行以下操作:

foreach ($query  as  $rec){
    <title><?php echo $rec->title ?></title>
}

将 'title' 替换为数据库中保留信用卡标题的列的名称...因此您将 运行 在控制器中的查询结果传递给此视图,然后使用 foreach 循环显示特定信用卡的数据

试试这个

  1. 模型已更改
  2. 控制器已更改。

模型中

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;
    }
}

在控制器中

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');
    }

}

在视图中

<?php echo (!empty($page_title)) ? $page_title : ''; ?> # Changed 

为了健壮性可以使用模板库,使用方法如下:

控制器

$this->template->title('Home :: ' . $this->data['metadata']['site_name'])
            ->set_layout('home_layout')
            ->build('listing_card', $this->data);

观看次数

    <title><?php echo $template['title']; ?></title>
    <?php echo $template['metadata']; ?>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

参考:https://github.com/philsturgeon/codeigniter-template

您可能需要为您的 show 函数创建一些路由。 Codeigniter URI Routing

$route['your_controller_name/show/(:any)'] = 'your_controller_name/show/';

我不确定您是否为您的主目录设置了 htaccess,以便您可以从 url.

中删除 index.php

试试下面的代码

型号:

<?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;
    }
}

}

控制器: 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');
    }
}

查看:

<head>
<title><?php echo $title;?></title>
</head>

控制器:

$data["page_title"] = $result[0]['title_field'];

查看: 你只需要在你的头文件中写下:

<title><?php echo $page_title; ?></title>

在您的模型中 - 不要 return $query->result(),只需 return $query:

function get_card($card = FALSE)
{
    $query = $this->db->get_where('creditcards', array('slug' => $card), 0,1);
    return $query;
}

控制器:

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');

    }    

}

控制器

 $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);

查看

<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>

创建一个基本控制器。默认位置是 application/core/MY_Controller.php => 这可以通过配置更改。 通过使用 $this->site_data,您可以在基础 class 中添加变量,并在每个 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');
    }
}

而且我认为你的 get_where 是错误的:

$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

你的上限是 0

function get_card($card = FALSE)
{
    $query = $this->db->get_where('creditcards', array('slug' => $card), 1,0);//limit 1 offset 0
    return $query->result();
}

访问您视图中的数据

<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>

试试这个:

function get_card($card = FALSE)
{
    $data = $this->db->get_where('creditcards', array('slug' => $card), 0,1)->result();
    $data->title = $data[0]->title;
    return $data;
}

控制器

$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;

查看

<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>

您可以创建一个基本控制器并将所有其他控制器扩展到该基本控制器。

像这样

<?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');


    }
}       

然后在你的控制器中

class Test extends MY_Controller
{
  function __construct() {

        parent::__construct();
         $this->data['meta_title'] = 'Your Title';

 }

}

并且在您的视图中访问这样的页面标题:

echo("<title>.$site_name.</title>");

再补充一点,这没有理由不起作用:

$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

在您看来:

<title><?=isset($page_title) ? $page_title : "";?></title>

如果这不起作用,则您的查询不会返回您认为的结果。

  • 我在从 CI_ControllerMY_Controller 扩展新控制器时调用 parent 构造函数,以便我可以享受在整个项目中共享的更高变量声明。
  • 我建议创建通用模型方法,以便它们具有更大的实用性,并且可以被项目中的许多控制器re-used使用。
  • 为了更容易将 header 数据加载到项目中的所有控制器中,我建议在 MY_Controller 中声明一些默认 header 数据,然后在较低级别的控制器中,您可以修改该数据并将其传递给视图。

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>";
}