Home  >  Article  >  Backend Development  >  Solve the problem that hobbies cannot be displayed in the PHP database

Solve the problem that hobbies cannot be displayed in the PHP database

WBOY
WBOYOriginal
2024-02-29 15:15:031156browse

Solve the problem that hobbies cannot be displayed in the PHP database

In order to solve the problem that hobbies cannot be displayed in the PHP database, you first need to confirm whether the data in the database is stored correctly and whether the connection is successful. When performing database queries, you need to ensure that the code is correct and the logic is clear to avoid errors that may prevent hobbies from being displayed. Next, I'll give you a concrete code example to solve this problem.

First, assume we have a user table that contains the user's ID, name, and hobby fields. Our goal is to query the user's interests from the database and display them on the page.

The following is a sample code for connecting to the database and querying the user's hobbies:

<?php
// 设置数据库连接参数
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("数据库连接失败: " . $conn->connect_error);
}

// 查询用户表中的爱好字段
$sql = "SELECT name, hobbies FROM users";
$result = $conn->query($sql);

// 检查是否查询成功
if ($result->num_rows > 0) {
    // 输出数据
    while($row = $result->fetch_assoc()) {
        echo "姓名: " . $row["name"]. " - 爱好: " . $row["hobbies"]. "<br>";
    }
} else {
    echo "0 结果";
}

// 关闭数据库连接
$conn->close();
?>

In the above code, we first establish the database connection and then query the name and hobbies in the user table fields and output them to the page through loop traversal. If the query is successful, the name and hobbies of each user will be output; if the query fails, "0 results" will be output.

Through the above code examples, you can modify the corresponding database connection parameters, query statements and page output content according to your specific situation to solve the problem that hobbies cannot be displayed in the PHP database. I hope this example can help you solve your problem smoothly.

The above is the detailed content of Solve the problem that hobbies cannot be displayed in the PHP database. 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