How can prepared statements be utilized in PHP to prevent SQL injection vulnerabilities in form submissions?

SQL injection vulnerabilities can be prevented in form submissions by using prepared statements in PHP. Prepared statements separate SQL code from user input, preventing malicious SQL queries from being executed. This helps protect the database from unauthorized access or manipulation.

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

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

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

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