Home >Backend Development >PHP Tutorial >How to query a database and display the results using PHP
Steps to use PHP to query the database and display the results: connect to the database; query the database; display the results, traverse the rows of the query results and output specific column data.
Using PHP to query the database and display the results involves the following steps:
1 . Connect to database
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }
2. Query database
$sql = "SELECT * FROM table_name"; // 执行查询 $result = $conn->query($sql); if (!$result) { die("查询失败: " . $conn->error); }
3. Display results
// 使用循环遍历查询结果的行 while ($row = $result->fetch_assoc()) { echo "ID: " . $row["id"] . "<br>"; echo "名称: " . $row["name"] . "<br>"; echo "邮箱: " . $row["email"] . "<br>"; echo "<br>"; }
Practical case: Obtaining and displaying user data
Suppose there is a database table named "users", which contains "id", "name" and "email" columns. You can query and display all user information using the following PHP code:
query($sql); if (!$result) { die("查询失败: " . $conn->error); } // 获取查询结果 echo "
ID | 名称 | 邮箱 |
---|---|---|
" . $row["id"] . " | " . $row["name"] . " | " . $row["email"] . " |
This will display a table in the browser with all user information.
The above is the detailed content of How to query a database and display the results using PHP. For more information, please follow other related articles on the PHP Chinese website!