What best practices should be followed when querying and displaying data from a MySQL database in PHP?

When querying and displaying data from a MySQL database in PHP, it is important to follow best practices to ensure security and efficiency. One key practice is to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize user input and validate data before executing queries. Finally, consider limiting the amount of data fetched from the database to improve performance.

// Example of querying and displaying data from a MySQL database using prepared statements

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

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

// Prepare a SQL query using a prepared statement
$query = $connection->prepare("SELECT name, email FROM users WHERE id = ?");
$id = 1;
$query->bind_param("i", $id);

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

// Bind the results to variables
$query->bind_result($name, $email);

// Fetch and display the data
while ($query->fetch()) {
    echo "Name: " . $name . " Email: " . $email . "<br>";
}

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