What are the common pitfalls when trying to display data from a database in PHP?
One common pitfall when displaying data from a database in PHP is not properly sanitizing input, which can lead to SQL injection attacks. To solve this issue, always use prepared statements or parameterized queries to securely interact with the database.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Prepare a statement
$stmt = $pdo->prepare("SELECT * FROM table WHERE column = :value");
// Bind parameters
$stmt->bindParam(':value', $value);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Display the data
foreach ($results as $row) {
echo $row['column_name'] . "<br>";
}
Related Questions
- What are some best practices for handling user-inputted text with line breaks in PHP?
- What are the benefits of using absolute paths like $_SERVER['SCRIPT_FILENAME'] instead of relative paths when handling active classes in PHP navigation menus?
- Why is using a CSS class preferred over the font tag when displaying different levels of importance in PHP?