如何在1行显示4个名称而不是PHP中新行的每个名称?

时间:2011-12-08 05:47:04

标签: php mysql

您好我一直在使用此代码从mysql数据库中获取数据并以列格式显示,即

a 
b
c

我想要的是每行显示4个名字,即

a b c d

e f g....

在这方面有人可以帮助我

三江源。

这是我的代码

<?php

$result = mysql_query("SELECT * FROM Persons");

echo "<table border='1'>";

while($row = mysql_fetch_array($result))
{
    echo "<tr>";
    echo "<td>" . $row['Name'] . "</td>";
    echo "</tr>";
}

echo "</table>";

mysql_close($con);
?>

3 个答案:

答案 0 :(得分:2)

使用modulus operator %

$i = 0;
while($row = mysql_fetch_array($result))
{
   $i++;
   if ($i % 4 == 0) {
      echo "<tr>";
   }
   echo "<td>" . $row['Name'] . "</td>";
   if ($i % 4 == 0) {
      echo "</tr>";
   }
}

作为奖励,您的代码中出现语法错误。看看这一行

echo "<table border='1'>;

其中 应该是

echo "<table border='1'>";

答案 1 :(得分:1)

$cnt = 0;

while($row = mysql_fetch_array($result))
{
  if($cnt%4==0) echo "<tr>";
  echo "<td>" . $row['Name'] . "</td>";
  $cnt++;
}

答案 2 :(得分:0)

    <?php
    $con = mysql_connect("localhost","user","abc123");
    if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("my_db", $con);

    $result = mysql_query("SELECT * FROM Persons");

   ?>
   <table border='1'>
   <tr>
   <?php
    $count=1;
    while($row = mysql_fetch_array($result))
    {
    if($count%4==0)
    { ?>
    </tr><tr>
    <?php }
    <td><?php echo $row['Name']; ?></td>
    $count++;    
    }
    ?>
    </tr>   
    </table>
    <?php    
    mysql_close($con);
    ?>
相关问题