How to display database content in PHP?
In order to display database content in PHP, you need to connect to the database, execute a query, and then display the results. Here is an example code:
// 连接到数据库
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 执行查询
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
// 检查查询结果是否为空
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 结果";
}
// 关闭数据库连接
$conn->close();
In the code above, we start by connecting to the database and then executing a query statement to select the data we want to display. If the query result is not empty, we use a loop to iterate through each row and output the data in each row. Finally, we close the database connection.
Please note that the database connection information (server name, username, password, and database name) in the example above may need to be modified according to your specific situation.