Home > Article > Backend Development > How to implement data collection and display through PHP and database
How to implement data collection and display through PHP and database
Introduction:
In today's era of information explosion, data collection and display are essential for various applications. It's all very important. PHP and database are two powerful tools that can help us realize data collection and display functions. This article details how to use PHP and a database to accomplish this task, along with code examples.
1. Database configuration and connection
The first thing to do is to configure the database information and establish a connection with the database. In PHP, we can use MySQLi or PDO extensions to achieve this functionality. The following is an example of using MySQLi extension:
<?php $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "database_name"; // 创建数据库连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("数据库连接失败: " . $conn->connect_error); } ?>
2. Data collection
After connecting to the database, we can collect data by executing SQL query statements. The following is a simple example that demonstrates how to query and obtain some data from the database:
<?php $sql = "SELECT * FROM table_name"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>"; } } else { echo "没有数据"; } $conn->close(); ?>
3. Data display
After obtaining the data, we can use HTML and PHP to display the data. The following is a simple example that displays the queried data in a table:
<!DOCTYPE html> <html> <head> <title>数据展示</title> <style> table { border-collapse: collapse; width: 100%; } th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; } </style> </head> <body> <table> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <?php while($row = $result->fetch_assoc()) { echo "<tr>"; echo "<td>".$row["id"]."</td>"; echo "<td>".$row["name"]."</td>"; echo "<td>".$row["age"]."</td>"; echo "</tr>"; } ?> </table> </body> </html>
Summary:
Through PHP and database, we can easily realize the data collection and display functions. The above sample code shows how to configure a database connection, collect data, and display the data on a web page. I hope this article can help you understand how to use PHP and databases to collect and display data. If you have other questions or needs, please feel free to contact us. Thanks!
The above is the detailed content of How to implement data collection and display through PHP and database. For more information, please follow other related articles on the PHP Chinese website!