我想创建一个“php-mysql”系统,管理员可以在其中创建类别和产品。产品将动态存储在它们所属的类别中,并且在用户界面上,这些产品将准确显示在它们所属的类别下方。例如:现在我的产品显示如下图:
我希望它们显示如下图所示:
我的 mysql 表是: 对于类别:
对于产品:
到目前为止我的代码(sql)是:
function getCategory($category){
$db_conn=getConnection();
if(!$db_conn)return false;
$sql="SELECT * from products where name='$category'";
$result=$db_conn->query($sql);
if($result->num_rows>0){
$db_conn->close();
return false;
}
}
function getProduct(){
$db_conn=getConnection();
if(!$db_conn)return false;
$sql="SELECT * from products";
$result=$db_conn->query($sql);
$db_conn->close();
return $result;
}
PHP 代码:
<div class="category">
<?php $categories=getCategory(); ?>
<?php while($category = $categories->fetch_assoc()) : ?>
<h2><?php echo $category['name'];?></h2>
<div class="products">
<?php $products=getProduct(); ?>
<?php while($product = $products->fetch_assoc()):?>
<table>
<tr><td><?php echo $category['name'];?></td></tr>
<tr><td><?php echo $category['image'];?></td></tr>
<tr><td><?php echo $category['price'];?></td></tr>
</table>
最佳答案
将 getProduct() 函数更改为以下内容,以便您根据类别获取产品。
function getProduct($category){
// Fill the details appropriately or pass a db instance
$db_conn = getConnection();
// Check connection
if ($db_conn->connect_error) {
die("Connection failed: " . $db_conn->connect_error);
}
$sql = "SELECT * from products WHERE category = ?";
// Execute query
$stmt = $db_conn->query($sql);
$stmt->bind_param("s", $category);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$result = $result->fetch_assoc(); // fetch data
return $result;
}
在 HTML 中,执行以下操作:
<div class="category">
<?php $categories=getCategory(); ?>
<?php while($category = $categories->fetch_assoc()) : ?>
<h2><?php echo $category['name'];?></h2>
<div class="products">
<?php $products=getProduct($category['name']); ?>
<?php while($product = $products->fetch_assoc()):?>
<table>
<tr><td><?php echo $product['name'];?></td></tr>
<tr><td><?php echo $product['image'];?></td></tr>
<tr><td><?php echo $product['price'];?></td></tr>
</table>
</div>
</div>
关于php - 准确地显示产品所属的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59852872/