What are the best practices for handling data retrieval and output in PHP scripts?

When handling data retrieval and output in PHP scripts, it is important to properly sanitize and validate user input to prevent SQL injection attacks. Additionally, using prepared statements when interacting with databases can help prevent security vulnerabilities. Finally, organizing and formatting the output data in a clear and structured manner can improve readability and user experience.

// Example of using prepared statements to retrieve data from a MySQL database

// Establish a connection to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");

// Bind the parameter values
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);

// Execute the query
$stmt->execute();

// Fetch and output the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "User ID: " . $row['id'] . "<br>";
    echo "Username: " . $row['username'] . "<br>";
    echo "Email: " . $row['email'] . "<br>";
}