我有代码从数据库中选择数据,然后将这些选择的值设置为一个变量。
但是我需要多次运行查询。我想知道我是否可以使用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'];
这可能吗?或者它是否值得去做?
为什么不直接使用数组来保存值呢?
你可以这样做
$name = 'c' . $type;
$$name = $row['cOutputValue'];
$name = 'p' . $type;
$$name = $row['pOutputValue'];
但是总的来说不是很方便,对于这种情况,数组可能更好。