What best practices should be followed when using mysql_real_escape_string in PHP?

When using mysql_real_escape_string in PHP, it is important to remember that this function is deprecated and should not be used. Instead, you should use parameterized queries with prepared statements to prevent SQL injection attacks. This involves using placeholders in the SQL query and binding the actual values separately.

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

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

// Set the parameter values and execute the query
$username = $_POST['username'];
$stmt->execute();

// Bind the result variables and fetch the results
$stmt->bind_result($result);
$stmt->fetch();

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