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


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

我正在CodeIgniter中编写一个应用程序,在该应用程序中,我在每个控制器的每个页面上指定<title>元标记,并将其发送到我的头模板。然而,现在我已经创建了一个应用程序,通过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文档,但到目前为止运气不佳。有什么解决方案吗?

试试这个

  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 

一个简单的例子:

控制器

$query = $this->Listing_model->get_card($card);
$query = $query->row();
$header["page_title"] = $query->title;

查看

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

创建一个基本控制器。它的默认位置是application/core/MY_Controller.php =>,可以通过配置进行更改。通过使用$this->site_data,您可以在基类中添加变量,并在每个控制器/视图中使用它们

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>

控制器

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

试试这个:

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>

您可能需要为您的show函数创建一些路由。代码点火器URI路由

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

我不确定你是否已经为主目录设置了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>

在您的登录卡视图中,执行以下操作:

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

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

您可以使用模板库来增强健壮性,并按如下方式使用:

控制器

$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

只是添加另一个,没有理由不起作用:

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

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

控制器:

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

视图:你只需要在你的头文件中写下:

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

在您的模型中-不要返回$query->result(),只返回$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');
    }    
}
  • 当我从CI_ControllerMY_Controller扩展新控制器时,我调用了父构造函数,这样我就可以享受在整个项目中共享的更高的变量声明
  • 我建议创建通用模型方法,以便它们具有更大的实用性,并且可以被项目中的许多控制器重复使用
  • 为了更容易将标题数据加载到项目中的所有控制器中,我建议在MY_Controller中声明一些默认标题数据,然后在较低级别的控制器中,您可以修改该数据并将其传递给视图

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