What are some best practices for generating tables and forms in PHP when displaying data from a database?

When generating tables and forms in PHP to display data from a database, it's important to properly sanitize user input to prevent SQL injection attacks. Use prepared statements to safely query the database and retrieve the data. When displaying the data in tables, use loops to iterate over the results and dynamically generate the rows. For forms, use input validation to ensure that only valid data is submitted to the database.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a statement to retrieve data from the database
$stmt = $pdo->prepare('SELECT * FROM mytable');
$stmt->execute();

// Generate a table to display the data
echo '<table>';
echo '<tr><th>Column 1</th><th>Column 2</th></tr>';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo '<tr>';
    echo '<td>' . htmlspecialchars($row['column1']) . '</td>';
    echo '<td>' . htmlspecialchars($row['column2']) . '</td>';
    echo '</tr>';
}
echo '</table>';

// Generate a form to submit data to the database
echo '<form method="post" action="submit.php">';
echo '<input type="text" name="data1" placeholder="Enter data 1" required>';
echo '<input type="text" name="data2" placeholder="Enter data 2" required>';
echo '<button type="submit">Submit</button>';
echo '</form>';
?>