What best practices should be followed when retrieving data from a MySQL database in PHP?

When retrieving data from a MySQL database in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, it is recommended to sanitize user input to prevent any malicious code from being executed. Finally, always handle errors properly to provide a more robust and secure application.

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Prepare a SQL query using a prepared statement
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $value);

// Sanitize user input
$value = filter_var($_POST['input'], FILTER_SANITIZE_STRING);

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

// Bind the results to variables
$stmt->bind_result($result1, $result2);

// Fetch and display the results
while ($stmt->fetch()) {
    echo $result1 . " - " . $result2 . "<br>";
}

// Close the statement and connection
$stmt->close();
$mysqli->close();