What are the benefits of using prepared statements or mysqli_real_escape_string to filter input data in PHP?

When dealing with user input in PHP, it is crucial to sanitize the data to prevent SQL injection attacks. Prepared statements and mysqli_real_escape_string are two common methods used to filter input data in PHP. Prepared statements provide a more secure way to interact with the database by separating SQL logic from data, while mysqli_real_escape_string escapes special characters in a string to make it safe for use in a SQL query.

// Using prepared statements to filter input data
$stmt = $mysqli->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);

$username = $_POST['username'];
$password = $_POST['password'];

$stmt->execute();

// Using mysqli_real_escape_string to filter input data
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);

$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($mysqli, $query);