How can SQL statements be securely executed in PHP to prevent SQL injection?

To prevent SQL injection in PHP, you can use prepared statements with parameterized queries. This method separates SQL code from user input, making it impossible for malicious input to interfere with the SQL query execution.

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

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

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

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

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