When using PHP for data query, sometimes it is necessary to display the sequence number of the query results to better understand the order of the data. This article will introduce how to use PHP's while statement to query and display the serial number.
Knowledge points needed:
First, we need to establish a database connection and perform query operations. Here is MySQL as an example:
//建立数据库连接 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); //检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } //查询数据 $sql = "SELECT * FROM myTable"; $result = $conn->query($sql);
Next, we can use the while statement to traverse the query results and display the sequence numbers in sequence. Use a count variable $i to record the number of rows currently traversed:
//遍历查询结果并显示序号 $i = 1; while($row = $result->fetch_assoc()) { echo "<tr>"; echo "<td>".$i."</td>"; echo "<td>".$row["name"]."</td>"; echo "<td>".$row["age"]."</td>"; //...其他表格内容 echo "</tr>"; $i++; }
In the while statement, use the fetch_assoc() method to obtain the data of each row, and display it in the HTML table through the echo statement. Among them, $i represents the serial number of the current row, which continues to increase as the traversal proceeds.
Finally, we need to add a serial number column to the HTML table to display the serial number of each row. A simple HTML table can be as follows:
<table> <tr> <th>序号</th> <th>姓名</th> <th>年龄</th> <!--...其他表头--> </tr> <?php //遍历查询结果并显示序号 $i = 1; while($row = $result->fetch_assoc()) { echo "<tr>"; echo "<td>".$i."</td>"; echo "<td>".$row["name"]."</td>"; echo "<td>".$row["age"]."</td>"; //...其他表格内容 echo "</tr>"; $i++; } ?> </table>
A serial number column is added to the table, and the other columns are the queried data columns. Use the while statement to display the query results row by row in the table.
At this point, the introduction to using PHP’s while statement to display the sequence number of query results is complete. Through the above method, we can easily display the query results by serial number and achieve a clearer data arrangement.
The above is the detailed content of How to use PHP's while statement to query and display serial numbers. For more information, please follow other related articles on the PHP Chinese website!