How can SQL injection vulnerabilities be mitigated in PHP scripts that involve user input?

SQL injection vulnerabilities in PHP scripts that involve user input can be mitigated by using prepared statements with parameterized queries instead of directly embedding user input into SQL queries. This approach helps to prevent malicious SQL code from being injected into the query and executed by the database.

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

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

// Set the user input
$username = $_POST['username'];

// Execute the query
$stmt->execute();

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process each row
}

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