What are the advantages of using mysqli over mysql_real_escape_string in PHP scripts?

When it comes to sanitizing user input in PHP scripts, using mysqli prepared statements is generally considered more secure than using mysql_real_escape_string. Mysqli prepared statements offer a more robust way to prevent SQL injection attacks by separating SQL logic from user input, while mysql_real_escape_string only escapes certain characters in a string. Additionally, mysqli prepared statements provide better performance and readability in code compared to mysql_real_escape_string.

// Using mysqli prepared statements to sanitize user input
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters
$stmt->bind_param("s", $username);

// Set parameter values
$username = $_POST['username'];

// Execute the statement
$stmt->execute();

// Fetch the result
$result = $stmt->get_result();

// Process the result
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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