点火器显示表 1 中的详细信息(如果等于表 2 中的特定类别)



我的数据库中有这个表,我们称之为table1,如下所示:

表1

另一个表格,我们将作为表 2:

表2

我想显示表 2 中的内容,但只显示表 2 中具有category_id匹配id的内容。

如何对控制器、模型和视图(仅相关部分)进行编码以实现此目的?

拜托,当涉及到 php 和代码点火器时,我是新手。顺便说一下,我正在使用代码点火器 3

有不同的方法可以做到这一点。

  1. 您可以在模型中创建两个单独的方法,用于从两个表中检索数据。然后将您的数据传递给视图并使用检查数据来显示正确的数据。

  2. 您可以将内部联接查询与 table2 一起使用,以检索特定数据,如下所示

join with table2 where table1.category_id = table2.id

它将更容易和高效。您将获得实际数据,并通过控制器将它们传递给视图,并在您想要的位置显示。

控制器:

if (!defined('BASEPATH')) exit('No direct script access allowed');
class Example extends CI_Controller
{ 
public function __construct() {
parent::__construct();
$this->load->model('Example_model');
}
public function index(){
$data['result'] = $this->Example_model->get_data();
$this->load->view('layout',$data);
}
}

型:

class Example_model extends CI_Model {
function __construct() 
{   
parent::__construct();
$this->load->database('default',TRUE);           
}
public function get_data(){
$this->db->join('tbale1','table.category_id=table2.id');
return $this->db->get('table2')->result();
}
}

视图:

<table>
<thead>
<tr>
<th>ID</th>
</tr>
</thead>
<tbody>
<?php
foreach($result as $key => $value){
?>
<tr>
<td><?php echo $value->category_id; ?></td>
</tr>
<?php } ?>
</tbody>
</table>

在模型中,您可以使用此方法。

public function your_method_name()
{ $sql = $this->db->query('SELECT * from table1, table2 where table1.id =table2.id);
return $sql->result();
}

在控制器中,可以使用此方法。

public function your_method_name(){
$this->load->your_model; //to load your model
$data['show'] = $this->your_model->your_method_name;
$this->load->view('your_view',$data);
}

你可以用foreach在你的视图中写。像这样的例子。

<?php foreach($show as $key){
echo $key->your_column_name;
?>

好了,大功告成。我希望这能解决你的问题。

相关内容

最新更新