How can escaping be used to enhance security in PHP scripts when using MySQLi?

Escaping user input is crucial in preventing SQL injection attacks when using MySQLi in PHP scripts. By properly escaping input using functions like mysqli_real_escape_string(), you can ensure that any special characters in the input are properly handled and do not pose a security risk.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Escape user input before using it in a query
$user_input = mysqli_real_escape_string($mysqli, $_POST['user_input']);

// Execute a query using the escaped input
$query = "SELECT * FROM users WHERE username='$user_input'";
$result = $mysqli->query($query);

// Process the query result
if ($result->num_rows > 0) {
    // Output the results
} else {
    // Handle no results
}

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