Current Location: Home> Latest Articles> How to Fix User Hobbies Not Displaying Properly from PHP Database

How to Fix User Hobbies Not Displaying Properly from PHP Database

M66 2025-07-22

Issue and Solution for User Hobbies Not Displaying Properly in PHP Database

In PHP development, it is common to fetch user hobby data from a database and show it on a webpage. However, the hobby field may contain multiple items or special characters, which often causes display problems such as garbled text or formatting issues. This article introduces an effective method along with detailed code examples to help you solve this problem easily.

Establishing Database Connection

First, you need to connect to the database. PDO or mysqli extensions are commonly used in PHP; here we use PDO as an example:

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Fetching User Information from Database

After successfully connecting, prepare an SQL statement to query users' basic info and their hobbies, then execute and store the results in an array:

<?php
$stmt = $conn->prepare("SELECT id, name, hobbies FROM users");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

Processing and Displaying User Hobbies

Since the hobbies field may include multiple comma-separated hobbies and special characters, process it before displaying. The example below splits the hobbies into an array, displays them as an HTML list, and escapes special characters:

<?php
foreach ($result as $row) {
    $hobbies = explode(',', $row['hobbies']);

    echo "<p>{$row['name']}'s Hobbies:</p>";
    echo "<ul>";
    foreach ($hobbies as $hobby) {
        echo "<li>" . htmlspecialchars($hobby) . "</li>";
    }
    echo "</ul>";
}
?>

This ensures that user hobbies, no matter how complex or containing special characters, are displayed correctly on the webpage.

Conclusion

This article has outlined common issues and solutions for displaying user hobbies from a PHP database. Using PDO for database connection, querying data, and handling the hobbies field by splitting and escaping special characters guarantees accurate and clear presentation, improving user experience. We hope this solution is helpful for your development needs.