Are there any alternative methods to mysqli_real_escape_string for preventing SQL injection in PHP?

SQL injection can be prevented in PHP by using prepared statements with parameterized queries. Prepared statements separate SQL code from user input, preventing malicious SQL code from being executed. This method is considered more secure than using functions like mysqli_real_escape_string.

// Using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

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

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

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

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

// Get result
$result = $stmt->get_result();

// Fetch data
while ($row = $result->fetch_assoc()) {
    // Handle data
}

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