PHP while循环(mysql_fetch_array)仅显示表中的最后一条记录

时间:2013-03-21 18:38:51

标签: php mysql while-loop

这是我的代码:

$result = mysql_query ($query) or die (mysql_error());
$row = mysql_fetch_assoc($result);

while($row = mysql_fetch_array( $result )) {

$contactID=$row['contactID'];
$contactFamily =$row ['contactFamily'];
$Contact=$row ['Contact'];
$contactOwner =$row ['contactOwner'];
$Impact=$row ['Impact'];
$Probability =$row ['Probability'];



if ($row ['Impact']=="5" && $row['Probability']=="4")
{
    $grid1=  $row ['contactFamily']." ".$row ['Contact']." .$row['contactOwner'];
}

?>
<br/>
<?php

if ($row ['Impact']=="3" && $row['Probability']=="4")
{
    $grid2=  $row ['contactFamily']." ".$row ['Contact']." .$row['contactOwner'];
}
?>
<br/>
<?

}

问题是当我回显$ grid1或$ grid2而不是全部回显时,它只显示表中的最后一条记录。

请有人帮忙吗?

4 个答案:

答案 0 :(得分:0)

$grid1$grid2需要是一个数组。否则,每次循环时,你只是覆盖你的价值。

$grid1 = array();
$grid2 = array();
while($row = mysql_fetch_array( $result )) {

$grid1[] =  $row ['contactFamily']." ".$row ['Contact']." ".$row['contactOwner'];

$grid2[] =  $row ['contactFamily']." ".$row ['Contact']." ".$row['contactOwner'];

答案 1 :(得分:0)

你应该在while循环中回显$ grid1和$ grid2,因为每次循环运行时,它们都会被下一个值覆盖。

答案 2 :(得分:0)

每次迭代结果集时,您都会使用您正在创建的字符串重新分配$grid1$grid2,这就是为什么只显示最后一个结果的原因。你想要做的是使用连接赋值运算符.=,例如

$grid1 .= $row['contactFamily']." ".$row['Contact']." ".$row['contactOwner'];

答案 3 :(得分:0)

您正在多次填充变量,但它只保留最后一个值,这就是您始终看到最后一个值的原因。我已经使用数组更改了代码:

<?php
$result = mysql_query($query) or die (mysql_error());
$row = mysql_fetch_assoc($result);
$i = 0
while($row = mysql_fetch_array($result)) {
    $data[$i]['contactID'] = $row['contactID'];
    $data[$i]['contactFamily'] = $row['contactFamily'];
    $data[$i]['Contact'] =$row['Contact'];
    $data[$i]['contactOwner'] = $row['contactOwner'];
    $data[$i]['Impact'] = $row['Impact'];
    $data[$i]['Probability'] = $row['Probability'];

    if ($row['Impact'] == "5" && $row['Probability'] =="4") {
        $grid1[$i] = $row['contactFamily'] . " " . $row ['Contact'] . " " . $row['contactOwner'];
    }
    if ($row['Impact']=="3" && $row['Probability']=="4") {
        $grid2[$i] = $row['contactFamily'] . " " . $row ['Contact'] . " " . $row['contactOwner'];
    }
    $i++;
}