How can one prevent SQL injection when handling user input in PHP forms, such as in the provided code snippet?

To prevent SQL injection when handling user input in PHP forms, one should use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate the SQL logic from the user input data, making it more secure and preventing malicious SQL injection attacks.

// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

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

// Prepare a SQL statement with a parameterized query
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);

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

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