How can one prevent SQL injection vulnerabilities when inserting user input into a database using PHP?

SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries in PHP. This method separates the SQL query from the user input, preventing malicious SQL code from being executed. By binding parameters to the query, the database engine can distinguish between the actual SQL command and user input.

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

// Bind the parameters with user input
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);

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