2017-02-25 172 views
0

我需要为视图生成一个url链接并将数据从数据库显示到此视图中。我的主要观点是艺术家/歌手,并有一张歌手表。每个歌手都应该是一个链接,当我按下他的专辑,传记和歌曲时,我会将他带到他的歌手页面。在Codeigniter中创建视图

我需要在Code Igniter中做到这一点,当然我可以阅读文档,但需要一个星期左右的时间,我只有2天。

这里是我的代码:

$this->load->database(); 

    $artists = $this->db->query('SELECT a.name, a.date, c.name FROM artist as a, country as c WHERE a.country_id=c.id'); 

    echo "<tr><td>Artist</td><td>Year</td><td>Country</td></tr>"; 

    foreach ($artists->result() as $row) 
    { 
     //echo $config['base_url']; 
     echo "<tr>"; 
     echo "<td><a href=\"/Artist.php\">" . $row->name . "</a></td>"; 
     echo "<td>" . $row->date . "</td>"; 
     echo "<td>" . $row->name . "</td>"; 
     echo "</tr>"; 
    } 
    echo "</table>"; 

回答

1

我会做一些这样的事

$autoload['libraries'] = array('database'); 
$autoload['helper'] = array('url'); 

型号

Example_model.php

<?php 

class Example_model extends CI_Model { 

public function getArtist() { 
    $artists = $this->db->query('SELECT a.artist_id,a.name, a.date, c.name FROM artist as a, country as c WHERE a.country_id=c.id'); 
    return $artists->result(); 
} 

} 

控制器示例

<?php 

class Example extends CI_Controller { 

    public function __construct() { 
    parent::__construct(); 
    $this->load->model('example_model'); 
    } 

    public function index() { 
    $data['artist'] = $this->example_model->getArtist(); 

    $this->load->view('example_view', $data); 
    } 

} 

然后在视图

<?php foreach($artist as $row) {?> 
<tr> 
<td><?php echo anchor('artist/' . $row->artist_id, $row->name, array('target' => '_blank'));?></td>"; 
<td>$row->date</td> 
<td>$row->name</td> 
</tr> 
<?php }?> 

然后在路线

$route['artist/(:any)'] = "controller/function/$1"; 
1

找到表艺术家的主键,用于expample ID或artist_id并添加查询

$artists = $this->db->query('SELECT a.artist_id,a.name, a.date, c.name FROM artist as a, country as c WHERE a.country_id=c.id'); 

,并在你的代码

foreach ($artists->result() as $row) 
{ 
    //echo $config['base_url']; 
    echo "<tr>"; 
    echo "<td><a href=\"/Artist.php?aid=" . $row->artist_id . "\">" . $row->name . "</a></td>"; 
    echo "<td>" . $row->date . "</td>"; 
    echo "<td>" . $row->name . "</td>"; 
    echo "</tr>"; 
} 
echo "</table>"; 

and in controler艺术家通过$ _GET获得数据['aid']

+0

我得到 “允许没有直接的脚本访问”。我肯定错过了什么。 – Vlad

1

我想你需要创建类似的路线,

$route['artist/(:any)'] = "controller/load_artist_page/$1"; 

,并在你的href标记,

base_url('artist/'.$parameter); 

,并在功能上得到id和加载视图,

function load_artist_page($artist_id){ 
//do processing and load view. 
} 

在传递它之前加密该ID。