0

我尝试使用此代码通过 PHP 将 MySQL 数据显示到编码的 HTML 表中:

<?php
    // Get all the data from the "login" table
    $result = mysql_query("SELECT * FROM login") or die(mysql_error());

    echo '<table class="table">
          <thead>
              <tr>
                  <th>FirstName</th> 
                  <th>LastName</th> 
                  <th>user</th> 
              </tr>
          </thead>
          <tbody>';

    // keeps getting the next row until there are no more to get
    while($row = mysql_fetch_array( $result )) {
        **if( $i % 2 == 0 )** {  //line 20
            $class = " class='odd'";
        }
        else {
            $class = "";
        }
        // Print out the contents of each row into a table
        echo "<tr" . $class . "><td>"; 
        echo $row['FirstName'];
        echo "</td><td>"; 
        echo $row['LastName'];
        echo "</td><td>"; 
        echo $row['user'];
        echo "</td><td>";  
    }
    echo "</tbody></table>";
?>

但它向我显示了这个错误:

未定义变量:第 20 行中的 i

在上面的代码中,第 20 行错误文本被标记为粗体。

4

4 回答 4

1

$i=0;在循环开始之前添加while,并在循环结束$i++之前增加它。while

$i = 0;

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

//your code

  $i++;
}
于 2013-02-24T07:19:00.917 回答
1

尝试这个

 $i=0;
 while($row = mysql_fetch_array( $result )) {
    if( $i % 2 == 0 ) {
        $class = " class='odd'";
    } else {
        $class = "";

    }
    // Print out the contents of each row into a table
    echo "<tr" . $class . "><td>"; 
    echo $row['FirstName'];
    echo "</td><td>"; 
    echo $row['LastName'];
    echo "</td><td>"; 
    echo $row['user'];
    echo "</td><td>";  
  $i++;
} 
于 2013-02-24T07:22:22.047 回答
0

添加

$i = 0;

while您收到错误之前并在您的评估中使用 $i++

于 2013-02-24T07:17:44.170 回答
0

你从来没有增加你的$i

$i = 0; 

while($row = mysql_fetch_array( $result )) {
  if($i % 2 == 0)
  ....

  $i++;  //You need to increment your $i
}
于 2013-02-24T07:18:23.627 回答