What steps can be taken to troubleshoot and resolve issues with displaying data from a database in PHP when encountering unexpected characters or errors?

When encountering unexpected characters or errors while displaying data from a database in PHP, one common issue could be related to character encoding mismatches. To troubleshoot and resolve this, you can set the correct character encoding for your database connection and ensure that the data is properly encoded and decoded when fetching and displaying it.

// Set the correct character encoding for the database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->set_charset("utf8");

// Fetch data from the database and ensure proper encoding/decoding
$query = "SELECT * FROM table";
$result = $mysqli->query($query);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data = utf8_encode($row['column_name']);
        echo $data;
    }
} else {
    echo "No results found";
}

$mysqli->close();