How can prepared statements be utilized to prevent SQL injection in PHP when inserting data into a database?

SQL injection can be prevented in PHP by using prepared statements. Prepared statements separate the SQL query from the user input, preventing malicious SQL code from being injected into the query. This is achieved by binding parameters to the query before execution.

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

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

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

// Set the values of the parameters
$username = $_POST['username'];
$password = $_POST['password'];

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