Is using mysql_real_escape_string enough to prevent SQL injections in PHP?

Using `mysql_real_escape_string` is not enough to prevent SQL injections in PHP. It is recommended to use prepared statements with parameterized queries to fully protect against SQL injections. Prepared statements separate SQL code from user input, making it impossible for an attacker to inject malicious SQL code.

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

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

// Using prepared statements to prevent SQL injections
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();

// Fetch result
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process the fetched data
}

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