What potential pitfalls should be considered when retrieving and displaying data from a database in PHP?
One potential pitfall when retrieving and displaying data from a database in PHP is SQL injection attacks, where malicious code is injected into SQL statements. To prevent this, always use prepared statements with parameterized queries to sanitize user input.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the parameter
$stmt->bindParam(':username', $_POST['username']);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Display the results
foreach ($results as $row) {
echo $row['username'] . '<br>';
}