What are some best practices for handling and displaying data from relational databases in PHP scripts?

When handling and displaying data from relational databases in PHP scripts, it is important to use parameterized queries to prevent SQL injection attacks. Additionally, it is recommended to sanitize user input to prevent cross-site scripting (XSS) attacks. It is also good practice to properly handle errors and exceptions when interacting with the database.

// 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);
}

// Prepare and execute a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

// Display the data
while ($row = $result->fetch_assoc()) {
    echo "Name: " . $row["name"] . "<br>";
    echo "Email: " . $row["email"] . "<br>";
}

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