gpt4 book ai didi

php - 如何获取数据库中的数据并在View中显示具体数据(Codeigniter)

转载 作者:行者123 更新时间:2023-11-29 07:37:57 25 4
gpt4 key购买 nike

我是 Codeigniter 框架的新手,我创建了一个简单的应用程序,它将从数据库中获取数据,然后在 View 中显示条件。我正在尝试将数据库中的特定数据显示到我的 View 中,到目前为止,我没有使用下面的代码。

模型(Datamodel.php)

function getData() {
$this->db->select("name, value");
$this->db->from('settings');
$query = $this->db->get();
return $query->result_array();
}

Controller (maincontroller.php)

function index()
{
$data['metadata'] = $this->Datamodel->getData();
$this->load->view('viewdata', $data);
}

查看

  <h3>Site Information</h3>
<?php foreach($metadata as $data) {?>
<h4>Site Title: <?php echo $data['site_title']; ?></h4>
<h4>Site Description: <?php echo $data['site_description']; ?></h4>
<h4>Site keyword: <?php echo $data['site_keyword']; ?></h4>
<h4>Site Year: <?php echo $data['site_year']; ?></h4>
<?php }?>

我想在浏览器上显示类似这样的内容:

站点信息

网站标题:我的第一个 codeigniter 应用
站点描述:这是示例 ci 应用程序
站点关键字:简单的ci应用程序,第一个应用程序
网站年份:2015

{ 接受任何帮助和建议。谢谢!请看这张图片[http://prntscr.com/722hsm ] 我的数据库结构!}

最佳答案

感谢您的主动行动。

只是一些修改:

型号

<?php
function getData() {
$siteData = array();
$this->db->select("name, value");
$this->db->from('settings');
$query = $this->db->get();
if ($query->num_rows()) {
foreach ($query->result_array() as $row) {
// Your data is coming from multiple rows, so need to loop on it.
$siteData[$row['name']] = $row['value'];
}
}
return $siteData;
}

查看:

<h3>Site Information</h3>
<?php foreach($metadata as $dataName => $dataValue) {?>
<!-- You are getting the names and values in loop, so,
use it in loop. Also, use ucwords() and str_replace() to beautify your
output. for more informtion on this, read php.net documentation.
-->
<h4><?php echo ucwords(str_replace('-', ' ', $dataName))?>: <?php echo $dataValue; ?></h4>
<?php }?>

第二种方法(不使用 FOREACH):

<h3>Site Information</h3>
<h4>Site Title: <?php echo $metadata['site_title']; ?></h4>
<h4>Site Description: <?php echo $metadata['site_description']; ?></h4>
<h4>Site keyword: <?php echo $metadata['site_keyword']; ?></h4>
<h4>Site Year: <?php echo $metadata['site_year']; ?></h4>

关于php - 如何获取数据库中的数据并在View中显示具体数据(Codeigniter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30068051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com