snippetphpMinor
Create a table from MySQL using PHP PDO
Viewed 0 times
createphpmysqlusingfromtablepdo
Problem
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:
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
foreachandwhilebeing used...
field1
field2
field3
field4
field5
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);
?>
$row) : ?>
Solution
- The
fetch()call only calls a single row from result set.
- Your
foreachloop will, as a result, just go in the first result and do nothing. It may even produce an error/notice for undefined index in$row.
- While using a
SELECTstatement in PHP, always include the specific columns that you want to fetch. This is among good practices.
$sth = $dbh->prepare("SELECT `field1`, `field2`, `field3`, `field4`, `field5` FROM a_temp");
$sth->execute();
?>
fetch(PDO::FETCH_ASSOC) as $row) : ?>
Or, if you want to use a while loop:
$sth = $dbh->prepare("SELECT `field1`, `field2`, `field3`, `field4`, `field5` FROM a_temp");
$sth->execute();
?>
fetch(PDO::FETCH_ASSOC) ) { ?>
Code Snippets
$sth = $dbh->prepare("SELECT `field1`, `field2`, `field3`, `field4`, `field5` FROM a_temp");
$sth->execute();
?>
<?php foreach($sth->fetch(PDO::FETCH_ASSOC) as $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>$sth = $dbh->prepare("SELECT `field1`, `field2`, `field3`, `field4`, `field5` FROM a_temp");
$sth->execute();
?>
<?php while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) { ?>
<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 } ?>
</table>Context
StackExchange Code Review Q#24743, answer score: 4
Revisions (0)
No revisions yet.