What potential pitfalls should be considered when using PHP to interact with a database for frontend elements?

One potential pitfall when using PHP to interact with a database for frontend elements is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, always use prepared statements with parameterized queries to securely pass user input to the database.

// Example of using prepared statements to prevent SQL injection

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

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

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

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

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

// Use the results in frontend elements
foreach ($results as $row) {
    echo $row['username'];
}