【问题标题】:Loop in PHP not workingPHP中的循环不起作用
【发布时间】:2011-07-17 04:17:16
【问题描述】:
$qPhysician = mysql_query("SELECT * FROM physicians");
$num = mysql_num_rows($qPhysician);
$i=0;
while($i < $num)
{
    "<tr>";
    "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
    "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
    "</tr>";
    $i++;
}

我得到空白结果。

如果我回显$num,我会得到“19”,这是我的数据库中的行数。 如果我回显$rowPhysician['lastName'] 只是为了测试我是否获得记录,我会获得至少1 条姓氏记录。我不知道“while”是否有问题。请帮帮我。

【问题讨论】:

  • 你真的应该使用mysql_fetch_array。 mysql_num_rows 通常要慢得多。
  • @cwallenpoole - 我将如何运行它作为替代方案?请编码 :) 谢谢!

标签: php loops while-loop


【解决方案1】:

您是否错过了打印字符串的回声?

while($i < $num) {
    echo "tr";
    echo "td" . mysql_result($qPhysician,$i,"lastName") . "/td";
    echo "td" . mysql_result($qPhysician,$i,"firstName") . "/td";
    echo "/tr";
    $i++;
}

【讨论】:

  • 哦,呵呵!我完全忘记了那个回声!非常感谢 RHSeeger。现在我在嘲笑自己:)
  • 查看页面时没有报错吗?看日志是我调试php的第一步。
【解决方案2】:

从技术上讲,这不是答案,但以这种方式显示代码更容易:

// first, only take the records you need -- each record adds more time to
// query, so if you only need 2, only select 2.
$query = mysql_query("SELECT lastName, firstName FROM physicians");

// mysql_fetch_assoc returns an associative array of all of the columns
// mysql_fetch_row   returns a numerically indexed array.
// mysql_fetch_array returns an array with both numeric and string indexing.
// they will all return FALSE when there are no more results in the query.
while( $arr = mysql_fetch_assoc( $query ) )
{
    echo "<tr>";
    // Now, use array indexing.
    echo "<td>" . $arr[ "lastName" ] . "</td>";
    echo "<td>" . $arr[ "firstName" ] . "</td>";
    echo "</tr>";
}

mysql_result 实际上是一个更好的选择是非常罕见的情况——通常最好只在 PHP 中填充几个数组并使用数据库来完成。

【讨论】:

    【解决方案3】:

    无论如何,回显 HTML 是不好的做法。更正确的输出应该是这样的

    ...
    while($i < $num) :?>
        <tr>
          <td><?php echo mysql_result($qPhysician,$i,"lastName"); ?></td>
          <td><?php echo mysql_result($qPhysician,$i,"firstName") ?></td>
        </tr>
    <?php $i++; endwhile;
    ...
    

    请注意,您也写错了关闭 HTML。

    【讨论】:

    • “一堆错误”是一个错误的描述。如果你告诉我你得到了什么错误信息,我可以提供帮助。
    • 警告:mysql_result() [function.mysql-result]:无法跳转到第 33 行 C:\wamp\www\iPOC\physicians2.php 中 MySQL 结果索引 6 的第 3 行跨度>
    • 你忘了在循环之前放置$qPhysician = mysql_query("SELECT * FROM physicians"); $num = mysql_num_rows($qPhysician); $i=0; 吗?
    • 那些行仍在循环上方
    • 糟糕,$i++ 部分应该在循环的末尾。更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2016-11-03
    • 1970-01-01
    • 2012-04-15
    • 2013-07-06
    相关资源
    最近更新 更多