What are the differences between using mysqli_real_escape_string() and prepared statements in PHP for data sanitization and security?

When it comes to data sanitization and security in PHP, using prepared statements is generally considered more secure than using mysqli_real_escape_string(). Prepared statements separate the SQL query from the user input, preventing SQL injection attacks. On the other hand, mysqli_real_escape_string() only escapes special characters in the input string, leaving room for potential vulnerabilities.

// Using prepared statements for data sanitization and security
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a SQL statement
$stmt = $mysqli->prepare("INSERT INTO users (username, email) VALUES (?, ?)");

// Bind parameters and execute the statement
$stmt->bind_param("ss", $username, $email);
$username = "john_doe";
$email = "john.doe@example.com";
$stmt->execute();

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