How can escaping variables in a MySQL query improve the security and reliability of the PHP code?

Escaping variables in a MySQL query helps prevent SQL injection attacks by sanitizing user input. This improves the security and reliability of the PHP code by ensuring that malicious SQL code cannot be injected into the query.

// Example of escaping variables in a MySQL query using mysqli_real_escape_string
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Escape user input to prevent SQL injection
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

// Prepare SQL query
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";

// Execute query
$result = $conn->query($sql);

// Handle query results
if ($result->num_rows > 0) {
    // User found
} else {
    // User not found
}

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