PHP while循环不使用mysql_result

时间:2011-07-17 09:50:41

标签: php while-loop

我有医生查询:

// Primary Physician Query
$qPhysician = mysql_query("SELECT * FROM physicians ORDER BY lastName ASC, firstName ASC");
$rowPhysician = mysql_fetch_array($qPhysician);

// State Query for Physician
$idStatePhysician = $rowPhysician['idstate'];
$qStatePhysician = mysql_query("SELECT * FROM states WHERE idstate=$idStatePhysician");
$rowStatePhysician = mysql_fetch_array($qStatePhysician);

// City Query for Physician
$idCityPhysician = $rowPhysician['idcity'];
$qCityPhysician = mysql_query("SELECT * FROM cities WHERE idcities=$idCityPhysician");
$rowCityPhysician = mysql_fetch_array($qCityPhysician);

我有一个while循环来显示所有医生排到一个表:

$num = mysql_num_rows($qPhysician);
    $i=0;
    while($i < $num)
        {
        $idphysicians = $rowPhysician['idphysicians'];
        if ($i % 2 == 0){
        echo "<tr class='even' onclick=\"DoNav('physicianUpdate.php?idphysicians=$idphysicians');\">";
        }
        else{
        echo "<tr class='odd' onclick=\"DoNav('physicianUpdate.php?idphysicians=$idphysicians');\">";
        }
        echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
        echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
        echo "<td>"; 
        if(isset($rowPhysician['idcity'])){echo mysql_result($qCityPhysician,$i,"name");} else{}
        echo "</td>";
        $i++;
        }

我的问题是:我的医生表中有3行数据。每个都有一个“idcity”值,反映了我的City表中的idnumber。但是,第一行数据正确显示idcity = Name,但第二行和第三行出错:

Warning: mysql_result() [function.mysql-result]: Unable to jump to row 1 on MySQL result index 7 in C:\wamp\www\iPOC\physicians.php on line 55

另外,如果我在其中一行上有idcity的空白值,它也会产生错误。

请帮忙!提前谢谢!

2 个答案:

答案 0 :(得分:1)

问题是您使用mysql_result()单向结果。正确的解决方法是使用其中一个mysql_fetch_*()函数,检查while循环中返回的值。

while($row = mysql_fetch_array($qPhysician)) {
   ...
}

答案 1 :(得分:-1)

这样的事情可能会更好:

$qCityPhysician = mysql_query("SELECT * FROM cities WHERE idcities=$idCityPhysician");
$qCityPhysicians = array();
while($row = mysql_fetch_array($qCityPhysician)) {
   $qCityPhysicians[$row['idcity']] = $row['name'];
}
$qPhysician = mysql_query("SELECT * FROM physicians ORDER BY lastName ASC, firstName ASC");
$i=0;
while($row = mysql_fetch_array($qPhysician)) {
    if ($i % 2 == 0) {
        echo "<tr>";
        echo "<td>" . $row['lastName'] . "</td>";
        echo "<td>" . $row['firstName'] . "</td>";
        echo "<td>"; 
        if(isset($row['idcity'])) {
            echo $qCityPhysicians[$row['idcity']];
        }
        echo "</td>";
        $i++;
     }
 }