What steps should be taken to ensure proper output of database values in PHP scripts?

To ensure proper output of database values in PHP scripts, it is important to properly sanitize and validate the data retrieved from the database to prevent any security vulnerabilities. Additionally, using prepared statements when querying the database can help prevent SQL injection attacks. It is also recommended to properly handle any errors that may occur when retrieving or displaying database values.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve data from the database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data from each row
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
$conn->close();
?>