How important is it to properly escape external variables when incorporating them into SQL queries in PHP?

It is crucial to properly escape external variables when incorporating them into SQL queries in PHP to prevent SQL injection attacks. Failure to escape these variables can leave your application vulnerable to malicious attacks where an attacker can manipulate the SQL query to execute unauthorized commands on your database.

// Example of properly escaping external variables in a SQL query
$unsafe_variable = $_POST['user_input'];
$safe_variable = mysqli_real_escape_string($connection, $unsafe_variable);

$query = "SELECT * FROM users WHERE username = '$safe_variable'";
$result = mysqli_query($connection, $query);