What are some best practices for displaying data from a database in PHP?
When displaying data from a database in PHP, it is important to properly sanitize the data to prevent SQL injection attacks. One best practice is to use prepared statements with parameterized queries to securely interact with the database. Additionally, consider using a loop to iterate through the retrieved data and display it in a structured format on the webpage.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query
$stmt = $pdo->prepare('SELECT * FROM mytable');
$stmt->execute();
// Fetch and display the data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<p>Name: ' . htmlspecialchars($row['name']) . '</p>';
echo '<p>Email: ' . htmlspecialchars($row['email']) . '</p>';
}
Related Questions
- What are the advantages of treating a string as a one-dimensional array in PHP for character manipulation tasks?
- What are some resources or best practices for beginners to learn about reading and parsing RSS feeds in PHP?
- What are some best practices for handling file existence checks in PHP, especially when using if/elseif statements?