使用for循环从MySQL查询中逐步选择值

问题描述:

I am trying to use a for loop to select an incremental value with a MySQL query. I have included sample code below:

<?php

$day_1="sep_28";
$day_2="sep_29";
$day_3="sep_30";

$query = mysql_query("SELECT * FROM table WHERE id = '$id'");

while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++) 
    {
        $dayVar = "day_".$i;
        //$dayVarCount = $dayVar."_count"; // Don't really need this anymore, so removed.
        $dayVarCount = $row[$$dayVar];
        echo "$$dayVar.': '.$dayVarCount<p>"; // Edited.
    }      
}
?>

I think I am getting close, but when I run the code my page is showing this:

$day_1.': '.0

$day_2.': '.2

$day_3.': '.5

Any additional recommendations? Thanks for the great help!

我正在尝试使用for循环来选择带有MySQL查询的增量值。 我在下面列出了示例代码: p>

 &lt;?php 
 
 $ day_1 =“sep_28”; 
 $ day_2 =“sep_29”; 
 $ day_3 =  “sep_30”; 
 
 $ query = mysql_query(“SELECT * FROM table WHERE id ='$ id'”); 
 
while($ row = mysql_fetch_assoc($ query))
 {
for($ i  = 1; $ i&lt; = 3; $ i ++)
 {
 $ dayVar =“day _”。$ i; 
 // $ dayVarCount = $ dayVar。“_ count”;  //不再需要这个了,所以删除了。
 $ dayVarCount = $ row [$$ dayVar]; 
 echo“$$ dayVar。':'。$ dayVarCount&lt; p&gt;”;  //编辑。
} 
} 
?&gt; 
  code>  pre> 
 
 

我想我已经接近了,但是当我运行代码时,我的页面显示了这个 : p>

$ day_1。':'。0 p>

$ day_2。':'。2 p>

$ day_3。':'。5 p>

还有其他建议吗? 感谢您的大力帮助! p> div>

Try a variable variable:

for ($i = 1; $i <= 3; $i++) 
{
    $dayVar = "day_".$i;
    $dayVarCount = $dayVar."_count";
    $$dayVarCount = $row[$$dayVar];
    echo $$dayVar.': '.$$dayVarCount.'<p>'; // Edited.
}

This basically uses a string to reference a variable by its name.

Just think of it this way:

$variable = 'hello';

$string = 'variable';

echo $$string;
// Is the same thing as:
echo $variable;

// Because you can thing of $$string as ${$string} ---> $variable when {$string} is interpreted into 'variable'

http://php.net/manual/en/language.variables.variable.php

<?php

$day_1="January 1";
$day_2="January 2";
$day_3="January 3";

$query = mysql_query("SELECT * FROM dates WHERE id = '$id'");

while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++) 
    {
        $var = $."day_".$i;
        $day_$i_count=$row['$var'];
        echo "$day_$i: $day_$i_count<p>";
    }       
}
?>

You can try this code too.

Replace this line:

echo "$$dayVar.': '.$dayVarCount<p>";

with this:

echo $$dayVar . ': ' . $dayVarCount . '<br>';

That all seems overly complicated, but possibly I don't understand the question adequately. Would this work?

$day[1]="sep_28";
$day[2]="sep_29";
$day[3]="sep_30";

$query = mysql_query("SELECT * FROM table WHERE id = '$id'");

while ($row = mysql_fetch_assoc($query))
{
    foreach ($day as $day_str) 
    {
        echo $day_str . ':' . $row[$day_str] . '<p>';
    }      
}