gpt4 book ai didi

php - 使用自定义 PHP MVC 在另一个 foreach 循环中进行 foreach 循环

转载 作者:搜寻专家 更新时间:2023-10-31 21:07:23 24 4
gpt4 key购买 nike

我有表 1 产品 和表 2 供应商

表格结构是这样的:

产品

CREATE TABLE IF NOT EXISTS `products` (
`id_product` int(11) NOT NULL AUTO_INCREMENT,
`id_supplier` int(11) NOT NULL,
`name_product` varchar(20) NOT NULL,
PRIMARY KEY (`id_product`) )
ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

供应商

CREATE TABLE IF NOT EXISTS `suppliers` (
`id_supplier` int(11) NOT NULL AUTO_INCREMENT,
`name_supplier` varchar(11) NOT NULL,
PRIMARY KEY (`id_supplier`) )
ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

模型:(suppliers_model.php)

class Suppliers_Model extends Model{

public function fetchSuppliers(){
stmt = $this->db->prepare("SELECT * FROM suppliers");
$stmt->setFetchMode(PDO::FETCH_OBJ);
$stmt->execute();
return $stmt->fetchAll();
}
}

Controller (suppliers.php)

class Suppliers extends Controller{
function __construct(){
parent::__construct();
}

public function index(){
$this->view->Suppliers= $this->model->fetchSuppliers();
}
}

View :

<table>
<tr>
<th>ID</th>
<th>Name of supplier</th>
<th>List of products</th>
</tr>
<?php foreach($this->Suppliers AS $key=>$value):?>
<tr>
<td><?php echo $value->id_supplier; ?></td>
<td><?php echo $value->name_supplier; ?></td>
<td>
<?php foreach():?>
**HERE I Wante To display a liste of products**
1. Product A
2. Product B
etc....
<?php endforeach;?>
</td>
</tr>
<?php endforeach;?>

如何创建另一个模型和 Controller 来获取产品列表并传递值

$value->id_supplier

作为显示每个供应商的产品列表的条件?

我试过这段代码,但它不起作用

    public function listProducts($id_supplier){
stmt = $this->db->prepare("SELECT * FROM products WHERE id_supplier=$id_supplier");
$stmt->setFetchMode(PDO::FETCH_OBJ);
$stmt->execute();
return $stmt->fetchAll();

}

并将此代码添加到 Controller

$this->view->listProducts= $this->model->listProducts('id_supplier');

并尝试使用 foreach 循环遍历产品表来检索产品列表,但它不起作用

NB: Im working with a custom PHP MVC

最佳答案

由于您已经设置了模型方法来获取产品,只需在您的 Controller 中使用它即可。

不要尝试在 View 内进行调用,而应在 Controller 内进行。

Controller :

public function index()
{

$suppliers = $this->model->fetchSuppliers();
foreach($suppliers as &$s) {
$s->products = $this->model->listProducts($s->id_supplier);
}

$this->view->Suppliers = $suppliers;
}

那么在你看来,就继续你所拥有的吧:

<table>
<tr>
<th>ID</th>
<th>Name of supplier</th>
<th>List of products</th>
</tr>
<?php foreach($this->Suppliers AS $key=>$value):?>
<tr>
<td><?php echo $value->id_supplier; ?></td>
<td><?php echo $value->name_supplier; ?></td>
<td>
<?php foreach($value->products as $k => $p): ?>
<p><?php echo ($k + 1) '. ' . $p->product_name; ?></p>
<?php endforeach;?>
</td>
</tr>
<?php endforeach;?>
</table>

关于php - 使用自定义 PHP MVC 在另一个 foreach 循环中进行 foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30258127/

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