这是我昨晚试图为我的论坛 -> 主题关系做的事情。过程式编程很容易。基本上你想要实现的是:
程序编程:
function get_categories
{
//1. Perform database query for categories
$sql_categories = "SELECT * FROM categories ORDER BY category_id ASC";
$res_categories = mysqli_query($conn, $sql_categories);
//2. Return result
return $res_categories_classic;
}
function get_products
{
//3. Get the returned data from the categories query
$res_categories = get_categories();
while ($array_categories = mysqli_fetch_assoc($res_categories))
{
//4. Perform database query for products
$sql_forums = "SELECT * FROM products WHERE product_id = {$array_categories["category_id"]}";
$res_forums = mysqli_query($conn, $sql_forums);
//5. Display returned data from products
}
}
现在在 OOP PHP 中,如果你使用一个框架,这将取决于框架,但一般来说:
//1. Get all the Categories
public function get_categories()
{
$this->db->select('*');
$this->db->from('categories');
$this->db->order_by('category_id', 'asc');
$query = $this->db->get();
return $query->result_array();
{
//2. Get all the related products
public function get_products($category_id)
{
$products = $this->db->fetch("select * from Products where product_id={$category_id}");
return $products;
}
Category_ID可以通过URL作为参数提供,方法是单击类别的href,基本上使用框架,这将是小菜一碟,因为您已经设置了简单的路由。Vanilla 是一样的,但看起来像这个 website/categories.php?类别=1