How does escaping work in PHP when inserting data into a MySQL database?

When inserting data into a MySQL database in PHP, it is important to escape the data to prevent SQL injection attacks. This can be done using the mysqli_real_escape_string() function to properly escape special characters in the input data before inserting it into the database.

// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Escape user inputs for security
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
$age = $mysqli->real_escape_string($_POST['age']);

// Insert the escaped data into the database
$sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', '$age')";
if ($mysqli->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;
}

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