What are best practices for connecting to a MySQL database in PHP and handling query results?

When connecting to a MySQL database in PHP, it is best practice to use the mysqli extension or PDO (PHP Data Objects) for secure and efficient database operations. To handle query results, it is recommended to use prepared statements to prevent SQL injection attacks and to properly handle errors and exceptions.

// Connect to MySQL database using mysqli
$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 query using prepared statements
$stmt = $conn->prepare("SELECT id, name FROM users WHERE id = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

// Handle query results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

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