从mysql动态选择列

时间:2013-01-13 12:39:23

标签: php mysql dynamic

我有几个问题引领动态部分,但我认为这应该有意义

$memberID = 7;
$oreVolumePriceQuery = "SELECT od.oreID, od.oreType, od.name, od.inGameID, od.size, ir.officialCorpRate FROM oreData od JOIN itemRates ir ON od.inGameID = ir.typeID order by od.oreID asc";
$oreVolumePriceResult = mysql_query($oreVolumePriceQuery);
while($row = mysql_fetch_assoc($oreVolumePriceResult)){
    $oreType = $row['oreType'];
    $getRefiningRateQuery = "SELECT '$oreType' FROM memberData WHERE member_id = '$memberID'";
    $getRefiningRateResult = mysql_query($getRefiningRateQuery);
    while($row = mysql_fetch_assoc($getRefiningRateResult)){
    $refiningRate = $row['$oreType'];

第一个查询返回类似于下面的结果(实际上是31行,但是2就足够了)

oreID | oreType | name     | inGameID | size | officialCorpRate
 1    | veld    | veldspar | 1230     | 0.1  | 10.21
 2    | scor    | scordite | 1228     | .15  | 10.2

基于第一行,第二个查询最终成为

SELECT veld FROM memberData WHERE member_ID = '7'

此查询返回

的正确结果
veld
 .7

但是这一切都在最后一行分崩离析,它在那里动态地选择从查询中提取哪一列。有没有办法解决这个问题?

3 个答案:

答案 0 :(得分:2)

您正在定义两个相同的$ row名称,将第二次获取重命名为$ row1 forexemple

 while($row = mysql_fetch_assoc($oreVolumePriceResult)){
$oreType = $row['oreType'];
$getRefiningRateQuery = "SELECT '$oreType' FROM memberData WHERE member_id = '$memberID'";
$getRefiningRateResult = mysql_query($getRefiningRateQuery);
while($row1 = mysql_fetch_assoc($getRefiningRateResult)){
$refiningRate = $row1[$oreType];

答案 1 :(得分:0)

根据经验,当查询因未知原因失败时,您应始终添加mysql_error();。所以,试试这个,因为我做了3/4的改变:

$oreVolumePriceQuery = "SELECT od.oreID, od.oreType, od.name, od.inGameID, od.size, ir.officialCorpRate FROM oreData od JOIN itemRates ir ON od.inGameID = ir.typeID order by od.oreID asc";
$oreVolumePriceResult = mysql_query($oreVolumePriceQuery) or die(mysql_error());
while($row = mysql_fetch_assoc($oreVolumePriceResult)){
    $memberID = 7;
    $oreType = $row['oreType'];
    $getRefiningRateQuery = "SELECT '$oreType' FROM memberData WHERE member_id = '$memberID'";
    $getRefiningRateResult = mysql_query($getRefiningRateQuery) or die(mysql_error());
    while($row = mysql_fetch_assoc($getRefiningRateResult)){
    $refiningRate = $row['$oreType'];

答案 2 :(得分:0)

不会评估单引号中的变量,因此不是

$refiningRate = $row['$oreType'];
你可能想要

$refiningRate = $row[$oreType];

另外,您是否有理由不将memberData表加入原始查询?