What is the importance of properly escaping characters in SQL queries within PHP code?

Properly escaping characters in SQL queries within PHP code is crucial to prevent SQL injection attacks. By escaping special characters, you can ensure that user input is treated as data rather than executable SQL code. This helps protect your database from malicious queries that could potentially compromise its security.

// Connect to the 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);
}

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

// Prepare a SQL query using the escaped user input
$sql = "SELECT * FROM users WHERE username = '$user_input'";

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

// Process the results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Username: " . $row["username"];
    }
} else {
    echo "0 results";
}

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