How can PHP developers prevent SQL injection attacks when working with MySQL databases?

SQL injection attacks can be prevented by using prepared statements with parameterized queries in PHP when interacting with MySQL databases. This approach ensures that user input is properly sanitized and treated as data rather than executable SQL code, reducing the risk of malicious SQL injection attacks.

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

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

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

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

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