How can PHP developers effectively handle input validation and prevent SQL injection in their code?

To effectively handle input validation and prevent SQL injection in PHP, developers should always sanitize user input before using it in database queries. This can be done using functions like mysqli_real_escape_string() or prepared statements. Additionally, developers should use input validation functions to ensure that the data being submitted meets the expected format and type.

// Example of using prepared statements to prevent SQL injection

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

// Prepare a SQL statement with a placeholder for user input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind the user input to the placeholder
$stmt->bind_param("s", $username);

// Sanitize the user input
$username = mysqli_real_escape_string($mysqli, $_POST['username']);

// Execute the prepared statement
$stmt->execute();

// Fetch the results
$result = $stmt->get_result();

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

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