1

我有代码从我的数据库中选择数据,然后将这些选定的值设置为一个变量。

但是我需要多次运行查询。我想知道是否可以使用 while/for 循环将查询运行 x 次并使用 switch 函数相应地更改变量名称?我不确定这是否值得做,更不用说可能了,有什么想法吗?谢谢。

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

////////////////////////////////////////////////////////////////////////////////////////////////////
$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'];

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

4

2 回答 2

3

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

于 2011-12-07T10:57:52.480 回答
1

你可以这样做

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

但总的来说它不会很方便,数组可能更适合这种情况。

于 2011-12-07T11:00:09.397 回答