In Web development, tables are one of the commonly used elements. Whether used to present data, collect information, or perform calculations, tables are an indispensable tool. As a popular server-side programming language, PHP can obtain data by querying the database and fill it in a form to display to the user. This article will introduce how to fill in the form using PHP query results.
//连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); //检测连接是否成功 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
//查询数据 $sql = "SELECT * FROM students"; $result = mysqli_query($conn, $sql); //检测查询是否成功 if (mysqli_num_rows($result) > 0) { //输出每一行数据 while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>"; } } else { echo "0 results"; }
<table> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </table>
Then, we need to iterate through the query results in PHP code and fill each row of data into the table. The following is a sample code for filling the query results into the form:
//创建表格,并填入数据 echo "<table>"; echo "<tr>"; echo "<th>ID</th>"; echo "<th>Name</th>"; echo "<th>Age</th>"; echo "</tr>"; if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>" . $row["id"] . "</td>"; echo "<td>" . $row["name"] . "</td>"; echo "<td>" . $row["age"] . "</td>"; echo "</tr>"; } } else { echo "0 results"; } echo "</table>";
//连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); //检测连接是否成功 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } //查询数据 $sql = "SELECT * FROM students"; $result = mysqli_query($conn, $sql); //创建表格,并填入数据 echo "<table>"; echo "<tr>"; echo "<th>ID</th>"; echo "<th>Name</th>"; echo "<th>Age</th>"; echo "</tr>"; if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>" . $row["id"] . "</td>"; echo "<td>" . $row["name"] . "</td>"; echo "<td>" . $row["age"] . "</td>"; echo "</tr>"; } } else { echo "0 results"; } echo "</table>"; //关闭连接 mysqli_close($conn);
The above sample code is just a demonstration and developers can modify it according to their own needs. For example, you can use SQL statements to filter out data that meets specific conditions, or use CSS styles to beautify the appearance of tables, etc. I hope this article can provide some help to developers who use PHP query results to fill in forms.
The above is the detailed content of How to fill in the query results into the form in php. For more information, please follow other related articles on the PHP Chinese website!