将自动编号列添加到从mysql读取的php表中

时间:2014-11-16 13:16:38

标签: php sql auto-increment

我试图在我的第一列开始编号之前添加一列,从1开始编号。我试图将自动增量添加到此行 echo"" 。 $ row [' ss']。 ""; ,但这似乎不想工作。任何想法如何做到这一点?

我的代码如下所示:

$result = mysqli_query($con,"SELECT * FROM `results` WHERE Event='100' AND Gender='M' ORDER BY Performance ASC");

echo "<table border='0'>
<tr>
<th align='left'>Pos</th>
<th align='left'>Event</th>
<th>Performance</th>
<th>Wind</th>
<th>Place</th>
<th align='left'>Name</th>
<th align='left'>Surname</th>
<th>Age</th>
<th>Team</th>
<th>Meet</th>
<th>Date</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ss'] . "</td>";
echo "<td>" . $row['Event'] . "</td>";
echo "<td>" . $row['Performance'] . "</td>";
echo "<td>" . $row['Wind'] . "</td>";
echo "<td>" . $row['Pos'] . "</td>";
echo "<td width='100' align='left'>" . $row['Surname'] . "</td>";
echo "<td Width='100'>" . $row['Name'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Team'] . "</td>";
echo "<td>" . $row['Meet'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

3 个答案:

答案 0 :(得分:1)

在标题

中添加此行
<th align='left'>#</th>

这里是php代码

$count = 1;
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $count . "</td>";
echo "<td>" . $row['ss'] . "</td>";
echo "<td>" . $row['Event'] . "</td>";
echo "<td>" . $row['Performance'] . "</td>";
echo "<td>" . $row['Wind'] . "</td>";
echo "<td>" . $row['Pos'] . "</td>";
echo "<td width='100' align='left'>" . $row['Surname'] . "</td>";
echo "<td Width='100'>" . $row['Name'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Team'] . "</td>";
echo "<td>" . $row['Meet'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "</tr>";
//other code
$count=$count+1;
}

答案 1 :(得分:0)

更好的解决方案是使用变量计数器对您的行进行“编号”:

$counter = 1;

while($row = mysqli_fetch_array($result))
   echo "<td>" . $counter . "</td>";
   $counter++;
}

这是正确的方法,因为如果ss列是mysql自动增量,那么你的行不会被SORT编号,而是按插入顺序排列无论您应用任何排序,都要进入数据库。

答案 2 :(得分:0)

尝试使用 fetch_assoc

更改 fetch_array