Home  >  Article  >  Backend Development  >  How to query a database and display the results using PHP

How to query a database and display the results using PHP

王林
王林Original
2024-05-02 14:15:021163browse

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.

如何使用 PHP 查询数据库并显示结果

How to use PHP to query the database and display the results

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 "";
echo "";
while ($row = $result->fetch_assoc()) {
    echo "";
}
echo "
ID名称邮箱
" . $row["id"] . "" . $row["name"] . "" . $row["email"] . "
"; // 关闭连接 $conn->close(); ?>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn