PHP在一个表中输出多个表及其值

时间:2016-03-31 16:44:21

标签: php mysql checkbox foreach

我需要逐步向您展示我到目前为止所做的工作以及我希望实现的输出。

首先,我有一个名为商店的表格如下:

id | store_name
1    S1
2    S2
3    S3
4    S4

并且每个商店名称都有自己的表格,其中包含商品编号,数量,成本,销售价格和日期 - 其中一个如下:

Table Name : S1
id | item_no | qty | cost | sell | date
1      b1001   10     6      12     2015-3-31
2      b1002   12     6      12     2015-3-31
3      b1003   6      3      6      2015-3-30
4      b1004   4      5      10     2015-3-30

对于每个store_name表等等。

我的目标是我需要一个输出来比较每个商品编号每个商店的数量,并将它们列在彼此旁边,如下所示:

item_no | cost | sell | S1 | S2 | S3 | S4
b1001     10     12    10     9    8     N/A
b1002     6      12    6      3    N/A   N/A
b1003     3      6     6      6    N/A   12
b1004     5      10    4      N/A  10    10

请注意,上述商店是由用户请求选择的(可以是一个商店名称,也可以是所有商店名称),如下所示:

<form method="POST" action="Somewhere.php">
//Looping To show how many stores
<input type=checkbox name=store[] value={$row['stores_name']} style='width:20px; height:20px;'>{$row['stores_name']}
//End of Looping
</form>

提交到Somewhere.php后,我们必须找出通过foreach循环选择的商店:

$allstore = $_POST['store'];

   foreach ($allstore as $store=>$value) {

//Don't Know what code should be here

}

我尝试过自己的方式,但是它将store_name表列在彼此之上,而不是我的目标。有办法吗?还有其他建议吗?

所有商店

请注意 COST 卖价是相同的!

1 个答案:

答案 0 :(得分:1)

您可以使用INNER JOIN从表中选择数据。

例如,使用此函数createSelect并使用表名中的键传递给它数组,即$allstore1 = ['S1' => 1, 'S2' => 2, 'S3' => 3]

<?php
function createSelect($allstore)
{
    if (empty($allstore))
        return "";

    $querySelect = "";
    $queryJoin = "";
    $baseTable = "";
    foreach ($allstore as $store => $value) {
        if (!$querySelect) {
            $baseTable = $store;
            $querySelect = "SELECT " . $store . ".item_no, " . $store . ".cost, " . $store . ".sell, " . $store . ".qty as " . $store;
        } else {
            $querySelect .= ", " . $store . ".qty as " . $store;
            $queryJoin .= "
             INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
        }
    }
    $querySelect .= " FROM " . $baseTable;
    $query = $querySelect . $queryJoin;

    return $query;
}

$allstore1 = ['S1' => 1, 'S2' => 2, 'S3' => 3];
$allstore2 = ['S1' => 1];
$allstore3 = [];

var_dump(createSelect($allstore1), createSelect($allstore2), createSelect($allstore3));

输出将是:

string(201) "SELECT S1.item_no, S1.cost, S1.sell, S1.qty as S1, S2.qty as S2, S3.qty as S3 FROM S1
             INNER JOIN S2 ON S1.item_no = S2.item_no
             INNER JOIN S3 ON S1.item_no = S3.item_no"
string(57) "SELECT S1.item_no, S1.cost, S1.sell, S1.qty as S1 FROM S1"
string(0) ""