php - 准确地显示产品所属的类别

标签 php mysql

我想创建一个“php-mysql”系统,管理员可以在其中创建类别和产品。产品将动态存储在它们所属的类别中,并且在用户界面上,这些产品将准确显示在它们所属的类别下方。例如:现在我的产品显示如下图:enter image description here

我希望它们显示如下图所示:

enter image description here

我的 mysql 表是: 对于类别:

enter image description here

对于产品:

enter image description here

到目前为止我的代码(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/

相关文章:

php - 将数组值从表单插入mysql

PHP MySQL 从两个表中选择数据并按第三个表中的字段排序

php - 重新定义内置 PHP 函数

php - PHP 中是否有等效的 print_r 或 var_dump 默认情况下不回显结果?

mysql - 在 MySQL 中使用带有变量的 concat() 函数

python - 'nan' python pandas 中的未知列 'field list'

php - sphinx 警告 : source src1: skipped 10 document(s) with zero/NULL ids

php - 从 mySQL 数据库显示单个值的更有效方法?

php - 为带有 TICKED 复选框的行运行 UPDATE 语句

PHP MySQL 编辑表单选择下拉列表预选