如何将列值与列名匹配?

时间:2019-01-08 11:29:25

标签: php mysqli

我正在尝试从shipping_charge表中获取价值。我有两个表,一个是pincode表,第二个是shipping_charge表。当用户输入密码时,我从pincode表中获取数据以检查区域。因此,我无法理解如何匹配提取的“区域”值来从shipping_charge表中获取运费。运输费用包括在citymetro列中。我以表格为例。

这是我的pincode桌子:

______________________
|id|pincode|cod|zone |
----------------------
|1 |100001 | Y |city |

|2 |100002 | N |City |

|3 |100003 | N |metro|

|4 |100004 | Y |City |

|5 |100005 | Y |City |

----------------------

这是我的shipping_charge桌子:

________________________
|id|pro_code|city|metro|
------------------------
|1 |pro0001 |100 |150  |

|2 |pro0002 |50  |100  |

|3 |pro0003 |150 |200  |

|4 |pro0004 |100 |120  |

------------------------

我仅尝试使用此代码来获取区域

$result= $this->connect()->query("SELECT * FROM wm_pincode WHERE 
pincode='$pincode'");
    if($result->num_rows>0){
        $row=$result->fetch_assoc();
        $zone =$row['zone'];
    }

如果用户输入pro_code= pro0002pincode=100003,则得到zone=metroshipping charge=100

怎么回事。

2 个答案:

答案 0 :(得分:0)

如果要使用两个查询:

$result= $this->connect()->query("SELECT * FROM wm_pincode WHERE 
pincode='$pincode'");
    if($result->num_rows>0){
        $row=$result->fetch_assoc();
        $zone =strtolower($row['zone']);
        $result= $this->connect()->query("SELECT $zone as shipping_charge_value FROM shipping_charge WHERE 
pro_code='$procode'");
        if($result->num_rows>0){
            $row=$result->fetch_assoc();
            $shipping_charge =$row['shipping_charge_value'];
        }
    }

答案 1 :(得分:0)

您可以使用union all

select charge,zone from (
select metro as charge,'metro' as namezone,pro_code from shipping_charge
  union all
select city as charge,'city' as namezone,pro_code from shipping_charge)
as DD,pincode sc where DD.pro_code='pro0002' and DD.namezone=sc.zone and sc.pincode=100003