将SQL查询/循环转换为PDO

时间:2013-08-07 12:53:47

标签: loops pdo foreach

我试图通过循环将PDO结果显示在表格中。但目前它只是显示一个白页。有什么缺失的建议吗?或者为什么页面是空白的?

<?php

try {  $conn = new PDO("pgsql:host=localhost port=5432 dbname=riverflies_gis", "opengeo", "opengeo");
 echo "PDO connection object created";
 echo "<br>";
}
catch(PDOException $e) {
  echo $e->getMessage();
}

  $sql  = "SELECT admin_name, adminuser_id, group_id FROM adminuser_tbl";
  $stmt = $conn->prepare($sql);
  $stmt->execute();
  $data = $stmt->fetchAll();
?>

        <table border='1' cellpadding='10'>
        <tr>
        <th>ID</th>
        <th>adminuser</th>
        <th>group_id</th>
        <th></th>
       </tr>

<?php foreach ($data as $row): ?>
<tr>
<td><?=$row['adminuser_id']?></td>
<td><?=$row['admin_name']?></td>
<td><?=$row['group_id']?></td>
</tr>
<?php endforeach ?>
</table>

1 个答案:

答案 0 :(得分:1)

永远数据库操作与 HTML 输出混合。

PDO特别适合它。首先获取您的数据:

$sql  = "SELECT admin_name, adminuser_id, group_id FROM adminuser_tbl";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();

然后将其输出到模板

<table border='1' cellpadding='10'>
 <tr>
  <th>ID</th>
  <th>First Name</th>
  <th>Last Name</th>
  <th></th>
  <th></th>
 </tr>
<? foreach ($data as $row): ?>
 <tr>
  <td><?=$row['id']?></td>
  <td><?=$row['firstname']?></td>
  and so on
 </tr>
<? endforeach ?>
</table>

看看你的输出代码有多漂亮和干净