php阻止特定的重复行

时间:2014-08-06 07:37:17

标签: php rows

我有一个示例PHP代码

  <?php 
   for ($x=0; $x<=3; $x++) {
    echo '<tr><td>Column $x</td>';
    $result = mysql_query(" SELECT id, `Nickname`,`hours` FROM `employee` ");

    echo '<table border=1>';
    while ($row = mysql_fetch_array($result)) {
      echo '<tr>';
      echo "<td>Nickname:".$row{'Nickname'}."</td><td>Hours: ".$row{'hours'}."</td>";
      echo '</tr>';
    }
    echo '</table>';    
    echo '</tr>';
   } 
?>

,结果是这样的。

                Column 1                    Column 2                   Column 3   
Nickname: John  Hours: 1  |  Nickname: John Hours:  1 | Nickname: John Hours: 1
Nickname: Foo   Hours: 2  |  Nickname: Foo  Hours:  2 | Nickname: Foo  Hours: 2 

我需要消除特定的重复行。我不需要重复昵称行。

输出应该是这样的                     第1栏第2栏第3栏     昵称:约翰时间:1 |时间:1 |营业时间:1     昵称:Foo小时:2 |时间:2 |时间:2

5 个答案:

答案 0 :(得分:3)

我的建议是你可以在PHP中轻松解决这个问题。

<?php 
for ($x=0; $x<=3; $x++) {

$result = mysql_query(" SELECT id, `Nickname`,`hours` FROM `employee` ORDER BY `Nickname`");

echo '<table border=1>';
$nick = "";
while ($row = mysql_fetch_array($result)) {
  if($nick != $row{'Nickname'} {
       if($nick != "") { echo '</tr>'; }
       echo '<tr>';
       echo "<td>Nickname:".$row{'Nickname'}."</td>";
  }
  echo "<td>Hours: ".$row{'hours'}."</td>";
  $nick = $row{'Nickname'};
}
echo '</table>'; 
?>

为了使其按预期工作,您必须在彼此旁边放置所有昵称,您可以使用ORDER BY昵称轻松完成。

答案 1 :(得分:0)

您应该删除For循环部分。另外你的代码应该是这样的:

<?php 

    $result = mysql_query("SELECT id, `Nickname`,`hours` FROM `employee`");

    echo '<table border=1>';
    while ($row = mysql_fetch_array($result)) {
      echo '<tr>';
      echo "<td>Nickname:".$row{'Nickname'}."</td><td>Hours: ".$row{'hours'}."</td>";
      echo '</tr>';
    }
    echo '</table>'; 
  ?>

尝试一下......

答案 2 :(得分:0)

试试这个   

    $result = mysql_query(" SELECT id, `Nickname`,`hours` FROM `employee` ");

    echo '<table border=1>';
    while ($row = mysql_fetch_array($result)) {
      echo '<tr>';
      echo "<td>Nickname:".$row['Nickname']."</td><td>Hours: ".$row['hours']."</td>";
      echo '</tr>';
    }
    echo '</table>'; 
  ?>

只需删除for循环

答案 3 :(得分:0)

只需更改您的SQL查询

SELECT id, `Nickname`,`hours` FROM `employee`

SELECT max(id) as id, `Nickname`, sum(`hours`) as hours FROM `employee` GROUP BY `Nickname`

另外,请注意不推荐使用mysql_query(http://php.net//manual/en/function.mysql-query.php)函数,你应该使用mysqli_query:

http://php.net/manual/en/mysqli.query.php

答案 4 :(得分:0)

我认为order by和lastName变量可以更好地解决

<?php 
for ($x=0; $x<=3; $x++) {

$result = mysql_query(" SELECT id, `Nickname`,`hours` FROM `employee` order by Nickname");

echo '<table border=1>';
$lastName='';
while ($row = mysql_fetch_array($result)) {
  echo '<tr>';
  if($row['Nickname']==$lastName)
  {
      echo "<td></td>";
  }
  else
  {
      echo "<td>Nickname:".$row{'Nickname'}."</td>";
      $lastName=$row['Nickname'];
  }
  echo "<td>Hours: ".$row{'hours'}."</td>";
  echo '</tr>';
}
echo '</table>'; 
?>