What are the best practices for escaping user input in PHP to prevent SQL injection vulnerabilities when querying a database?

To prevent SQL injection vulnerabilities in PHP, it is crucial to escape user input before using it in database queries. This can be achieved by using prepared statements with parameterized queries or by using functions like mysqli_real_escape_string() to sanitize user input.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Escape user input
$user_input = $mysqli->real_escape_string($_POST['user_input']);

// Prepare and execute the query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();

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

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