What are common pitfalls when accessing database data using PHP and HTML forms?

One common pitfall when accessing database data using PHP and HTML forms is not sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements or parameterized queries to securely interact with the database.

// Example of using prepared statements to access database data securely

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

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

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

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

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

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