为什么它循环多一次......我错过了什么

时间:2010-09-08 18:06:02

标签: php foreach

表中只有一条记录,所以为什么循环就像我有5个表,每个表有一个字母

$query = "Select * from click_tracker";
$result = mysql_query($query);
$all_clicks = mysql_fetch_array($result);

foreach($all_clicks as $click){
    print "
    <table border=\"1\">
      <tr>
        <th>Location</th>
        <th>Visit Count</th>
      </tr>
      <tr>
        <td>{$click['url_destination']}</td>
        <td>{$click['count']}</td>
      </tr>
    </table>";
}

这是返回的表

<table border="1">
  <tr>
    <th>Location</th>

    <th>Visit Count</th>
  </tr>
  <tr>
    <td>2</td>
    <td>2</td>
  </tr>
</table>

<table border="1">
  <tr>
    <th>Location</th>
    <th>Visit Count</th>
  </tr>
  <tr>
    <td>2</td>

    <td>2</td>
  </tr>
</table>
<table border="1">
  <tr>
    <th>Location</th>
    <th>Visit Count</th>

  </tr>
  <tr>
    <td>h</td>
    <td>h</td>
  </tr>
</table>
<table border="1">
  <tr>

    <th>Location</th>
    <th>Visit Count</th>
  </tr>
  <tr>
    <td>h</td>
    <td>h</td>
  </tr>

</table>
<table border="1">
  <tr>
    <th>Location</th>
    <th>Visit Count</th>
  </tr>
  <tr>
    <td>5</td>

    <td>5</td>
  </tr>
</table>
<table border="1">
  <tr>
    <th>Location</th>
    <th>Visit Count</th>

  </tr>
  <tr>
    <td>5</td>
    <td>5</td>
  </tr>
</table>   

5 个答案:

答案 0 :(得分:4)

mysql_fetch_array一个行作为数组提取。当您尝试使用foreach循环显示该结果时,实际上是在循环浏览所返回行的所有(实际上是两次,因为默认情况下为mysql_fetch_array返回一个包含数字和索引键的数组!)

如果你想得到所有结果集中的行(而且你很可能这样做),你需要使用while循环来继续获取行,直到不再存在:< / p>

$all_clicks = array();
while ($row = mysql_fetch_array($result))
{
  $all_clicks[] = $row;
}

然后当你迭代$all_clicks时,每次迭代都会有一个完整的行。

答案 1 :(得分:1)

mysql_fetch_array()返回行,看起来你的foreach循环遍历行中的字段而不是结果集中的行。

答案 2 :(得分:1)

您似乎正在打印多个表格。我不认为这是你想要的。您需要打印表格的开始和结束标记,以及循环外部的标题。您还应该在循环中调用mysql_fetch_array()而不只是一次。

print "
    <table border=\"1\">
      <tr>
        <th>Location</th>
        <th>Visit Count</th>
      </tr>";

$query = "Select * from click_tracker";
$result = mysql_query($query);

while ($click = mysql_fetch_array($result)) {
    print "
      <tr>
        <td>{$click['url_destination']}</td>
        <td>{$click['count']}</td>
      </tr>";
}

print "</table>";

您还应该考虑转发$click中的数据,但我不知道您的数据是什么样的,所以我不确定在while和{之间的区域放置什么{1}}陈述。

答案 3 :(得分:0)

你需要这样做:

$query = "Select * from click_tracker";
$result = mysql_query($query);
while($click = mysql_fetch_assoc($result)) {

答案 4 :(得分:0)

执行print_r($all_clicks)并检查结果是否符合预期。

如果只有一个结果,你真的不需要使用foreach。

 $query = "Select * from click_tracker";
    $result = mysql_query($query);
    $all_clicks = mysql_fetch_array($result);
     print "
        <table border=\"1\">
          <tr>
            <th>Location</th>
            <th>Visit Count</th>
          </tr>
          <tr>
            <td>{$all_clicks['url_destination']}</td>
            <td>{$all_clicks['count']}</td>
          </tr>
        </table>";