I am trying to simply present a table in HTML that is stored in a MySQL database. I would like to use Object Oriented PHP to access and fetch the data for the table. I have spent some time learning the different elements and have tried to put together a generic template I can use to access the tables in the database.
Questions:
- Is there anything wrong with the code below?
- Is there a better way to do this?
- Are there any redundancies in the code? Is a more generally preferred/standard way of doing this? I've seen
foreach
andwhile
being used...
<html> <table> <tr> <th>field1</th> <th>field2</th> <th>field3</th> <th>field4</th> <th>field5</th> </tr> <?php require_once 'db_config.php'; $dbh = new PDO($dsn, $dbuser, $dbpass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $sth = $dbh->prepare("SELECT * FROM a_temp"); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); ?> <?php foreach($result as $index => $row) : ?> <tr> <td><?php echo $row[field1]; ?></td> <td><?php echo $row[field2]; ?></td> <td><?php echo $row[field3]; ?></td> <td><?php echo $row[field4]; ?></td> <td><?php echo $row[field5]; ?></td> </tr> <?php endforeach;?> </table> </body> </html>