What are best practices for retrieving data from a MySQL database in PHP?

When retrieving data from a MySQL database in PHP, it is best practice to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, it is recommended to handle errors gracefully and close the database connection after retrieving the data.

// Create a database connection
$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 SQL query to retrieve data
$stmt = $conn->prepare("SELECT id, name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

$id = 1;
$stmt->execute();
$result = $stmt->get_result();

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

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