How does the separation of SQL code and data transfer work in the context of prepared statements in PHP PDO?

Separation of SQL code and data transfer is essential for preventing SQL injection attacks. Prepared statements in PHP PDO help achieve this separation by allowing you to define placeholders in the SQL query and bind parameters separately. This way, the SQL code remains static while the data is securely transferred to the database without the risk of malicious input.

// Example of using prepared statements in PHP PDO to separate SQL code and data transfer
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Define the SQL query with placeholders
$sql = "SELECT * FROM users WHERE username = :username";

// Prepare the statement
$stmt = $pdo->prepare($sql);

// Bind parameters
$username = $_POST['username'];
$stmt->bindParam(':username', $username, PDO::PARAM_STR);

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

// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}