php - 如何在一个函数内部调用另一个函数

标签 php mysql mysqli

我正在使用 PHP 和 MySQLi 制作自己的在线商店。基本上我有一个部分,用户可以在其中查看商店的所有品牌,并且还会显示表中存在的每个商品的数量。像这样的事情:

enter image description here

为了在屏幕上打印这些数据,我这样做了:

<?php 
    function get_brands(){
        $get_brands = "select * from brands";
        $run_brands = mysqli_query($GLOBALS['con'],$get_brands);
        while($row_brands = mysqli_fetch_array($run_brands)){
            $brand_id = $row_brands['brand_id'];
            $brand_title = $row_brands['brand_title'];
            echo " <li><a href='brands.php?brand_id=$brand_id'><span class='pull-right'><strong>(number items within this brand)</span>$brand_title</strong></a></li>";
        }
    }
?>

因此,因为我的数据库中有两个表,所以我需要调用此函数中的另一个函数来计算另一个表中的项目数。

其中一个表名为 products,其中包含品牌名称字段,另一个表名为 brands,如图所示:

enter image description here

那么如何做到这一点呢?有什么想法请提出来

最佳答案

在 while 循环内,您必须进行另一个数据库调用才能获取具有该品牌 ID 的商品总数。因此,打印内容的函数应该如下所示:

<?php 
function get_brands(){
    $get_brands = "select * from brands";
    $run_brands = mysqli_query($GLOBALS['con'],$get_brands);

    while($row_brands = mysqli_fetch_array($run_brands)){
        $brand_id = $row_brands['brand_id'];
        $brand_title = $row_brands['brand_title'];

        $totalNumberOfProductsQuery = "SELECT * FROM products WHERE brand_id = " . $brand_id;
        $brandProducts = mysqli_query($GLOBALS['con', $totalNumberOfProductsQuery);
        $totalProductsForBrand = mysqli_num_rows($brandProducts);

        echo " <li><a href='brands.php?brand_id=$brand_id'><span class='pull-right'><strong>$totalProductsForBrand</span>$brand_title</strong></a></li>";
    }
}

不知道复制和粘贴是否有效,但我希望您能明白。

关于php - 如何在一个函数内部调用另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48446374/

相关文章:

php - MySQL 服务器已消失 - 共享帐户

php - MySQL lower_case_table_names 导致 PHP 连接错误

javascript - 更新或插入数据后关闭弹出窗口

PHP Excel 导入

php - Selenium 不适用于 Firefox 57 on php

php - 使用 PHP 查询 MySQL 但数据库列有 $

PHP mysqli 在命令行中工作,但在页面上不工作

php - 如何在Elasticsearch中计算平均最小时间?

mysql - 从连接表中获取最大日期

php - 如何使用纯 SQL 实现 PHP 条件?