What are the best practices for handling MySQL queries and errors in PHP scripts like the one provided in the forum thread?

Issue: The provided PHP script does not handle MySQL queries and errors properly, which can lead to security vulnerabilities and unexpected behavior. To address this, it is important to use prepared statements to prevent SQL injection attacks and to properly handle errors to improve the script's reliability.

// Connect to MySQL database
$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 using prepared statements
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = "example_user";
$stmt->execute();
$result = $stmt->get_result();

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

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