What are Prepared Statements in PHP and how do they help prevent SQL injections?

Prepared Statements in PHP are used to execute SQL queries with parameters that are bound to placeholders. This helps prevent SQL injections by separating the SQL query from the user input, which is then treated as data rather than executable code. Prepared Statements automatically escape user input, making it safe to use in SQL queries.

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

// Prepare a SQL statement with a placeholder
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the parameter to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

// Fetch the results
$results = $stmt->fetchAll();