2011-12-07 110 views
1

我有代码从我的数据库中选择数据,然后将这些选定的值设置为一个变量。PHP:是否可以动态更改变量的名称?

但是我需要多次运行查询。我想知道是否可以使用while/for循环来运行查询x次并使用开关函数相应地更改变量名称?我不确定这是否值得做更不可能的任何想法?谢谢。

下面是我试图实现的代码,它工作正常。

//////////////////////////////////////////////////////////////////////////////////////////////////// 
$output1 = mysql_query(" 

SELECT `pOutputValue`,`cOutputValue` 
FROM `output` WHERE `teamID` = '$teamID' && `period` = '$currentStage' && `outputType`  = 'balance' 

")or die($output1."<br/><br/>".mysql_error()); 

//assign the text located at the logo field (the path of the logo) to a variable  $slogan 
while($row = mysql_fetch_assoc($output1)) 
{ 
$pBalance = $row['pOutputValue']; 
$cBalance = $row['cOutputValue']; 

} 



//////////////////////////////////////////////////////////////////////////////////////////////// 
$output2 = mysql_query(" 

SELECT `pOutputValue`,`cOutputValue` 
FROM `output` WHERE `teamID` = '$teamID' && `period` = '$currentStage' && `outputType`  = 'marketShare' 

")or die($output2."<br/><br/>".mysql_error()); 

//assign the text located at the logo field (the path of the logo) to a variable $slogan 
while($row = mysql_fetch_assoc($output2)) 
{ 
$pMarketShare = $row['pOutputValue']; 
$cMarketShare = $row['cOutputValue']; 

} 
////////////////////////////////////////////////////////////////////////////////////////////////// 
$output3 = mysql_query(" 

SELECT `pOutputValue`,`cOutputValue` 
FROM `output` WHERE `teamID` = '$teamID' && `period` = '$currentStage' && `outputType` = 'salePrice' 

")or die($output3."<br/><br/>".mysql_error()); 

//assign the text located at the logo field (the path of the logo) to a variable $slogan 
while($row = mysql_fetch_assoc($output3)) 
{ 
$pSalePrice = $row['pOutputValue']; 
$cSalePrice = $row['cOutputValue']; 

} 

?> 

但是,我试图通过变量名更新循环运行查询。

<?php 

$i = "0"; 

while($i<4) 

{ 

switch ($i) 

case "0"; 
$type = "balance"; 
break; 

case "1"; 
$type = "marketShare"; 
break; 

case "2"; 
$type = "salePrice"; 
break; 

case "3"; 
$type = "unitPrice"; 
break; 



$output = mysql_query(" 

SELECT `pOutputValue`,`cOutputValue` 
FROM `output` WHERE `teamID` = '$teamID' && `period` = '$currentStage' && `outputType` = '$type' 

")or die($output."<br/><br/>".mysql_error()); 

//assign the text located at the logo field (the path of the logo) to a variable $slogan 
while($row = mysql_fetch_assoc($output)) 
{ 
$c$type = $row['pOutputValue']; 
$p$type = $row['cOutputValue']; 


} 

的问题是如何更新变量名

$pBalance = $row['pOutputValue']; 
    $cBalance = $row['cOutputValue']; 

这甚至可能吗?或者它甚至值得这样做?

回答

3

为什么不使用数组来保存这些值?那么问题就变得微不足道了。

+0

啊好的,看着那个,我从不使用或学习阵列,因为我被他们弄糊涂了,也许我需要去正确地学习它们。谢谢 – NeverPhased

+0

因此,使用一个数组我可以进行一个查询并将所有值存储在一个数组中,然后将每个值分配给一个变量? – NeverPhased

+0

基本上,而不是$ pMarketShare和$ cMarketShare你可以有:$ marketShares ['p']和$ marketShares ['c'] – KingCronus

1

你可以像下面这样做

$name = 'c' . $type; 
$$name = $row['cOutputValue']; 
$name = 'p' . $type; 
$$name = $row['pOutputValue']; 

但总体来说不会是非常方便的,阵列可能是这样的情况更好。