如何调用另一个函数内部的函数

时间:2018-01-25 15:25:50

标签: 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

那怎么办呢?请知道

2 个答案:

答案 0 :(得分:0)

创建一个像这样的新功能

nvarchar

并在当前函数中调用它,就像这样。

function count_brands($tableName, $brandId){
    $brandsNum = "select count(*) from " . $tableName ." Where product_id = ". $brandId ." ";
    $count = mysqli_query($GLOBALS['con'],$brandsNum);
    return $count;
}

假设这两个函数在同一个文件中    如果这些功能在一个类中。所以你像这样引用它

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> ". count_brands('brands', $brand_id) . "</span>$brand_title</strong></a></li>
        ";
    }
}

答案 1 :(得分:0)

在您的while循环中,您必须进行另一次数据库调用以获取具有该品牌ID的项目总数。所以打印出来的函数应该是这样的:

[{'inputData1': 'inputData1ValueArray'}, {'targetData1': 'targetData1ValueArray'}, {'inputData1': 'inputData1ValueArray'}, {'inputData1': 'inputData1ValueArray'}, {'targetData1': 'targetData1ValueArray'}, {'inputData1': 'inputData1ValueArray'}, {'inputData1': 'inputData1ValueArray'}, {'targetData2': 'targetData2ValueArray'}, {'inputData1': 'inputData1ValueArray'}, {'targetData2': 'targetData2ValueArray'}, {'inputData1': 'inputData1ValueArray'}, {'inputData1': 'inputData1ValueArray'}, {'inputData1': 'inputData1ValueArray'}, {'targetData3': 'targetData3ValueArray'}, {'targetData3': 'targetData3ValueArray'}, {'targetData1': 'targetData1ValueArray'}, {'inputData2': 'inputData2ValueArray'}, {'targetData1': 'targetData1ValueArray'}, {'inputData2': 'inputData2ValueArray'}, {'inputData2': 'inputData2ValueArray'}, {'targetData2': 'targetData2ValueArray'}, {'inputData2': 'inputData2ValueArray'}, {'inputData2': 'inputData2ValueArray'}, {'targetData2': 'targetData2ValueArray'}, {'inputData2': 'inputData2ValueArray'}, {'targetData3': 'targetData3ValueArray'}, {'inputData2': 'inputData2ValueArray'}, {'inputData2': 'inputData2ValueArray'}, {'inputData2': 'inputData2ValueArray'}, {'targetData3': 'targetData3ValueArray'}]

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