簡単なデータベース参照ページの作成

 テーブルの内容を表示するWebページを作成しましょう。

○ プロジェクト

 プロジェクトを作成して確認してみましょう。

プロジェクトの種類 PHPプロジェクト
プロジェクト名 DBSample

○ ファイル

 次のPHPファイルをプロジェクトに追加してください。

ファイルの種類 PHPファイル
ファイル名 DBSample.php

サンプルダウンロード

○ プログラム

 次のようにプログラムを記述してください。

DBSample.php

  1. <!DOCTYPE html>
  2. <html lang="ja">
  3.  <meta charset="utf-8">
  4.  <head>
  5.   <title>データベースサンプル</title>
  6.  </head>
  7.  <body>
  8.   <table border="1">
  9.    <tr>
  10.     <th>書籍ID</th>
  11.     <th>カテゴリーID</th>
  12.     <th>書籍名</th>
  13.     <th>著者名</th>
  14.     <th>出版社名</th>
  15.    </tr>
  16. <?php
  17. try{
  18.  //データベースに接続する
  19.  $pdo = new PDO('mysql:host=localhost;dbname=books;charset=utf8;', 'root', '');
  20.  //SQL文を作成する
  21.  $sql = 'SELECT * FROM books';
  22.  //SQL文を実行する
  23.  $resultset = $pdo -> query($sql);
  24.  //取得したデータを表示する
  25.  foreach($resultset as $r){
  26. ?>
  27.    <tr>
  28.     <td><?php print($r['id']); ?></td>
  29.     <td><?php print($r['category_id']); ?></td>
  30.     <td><?php print($r['book_name']); ?></td>
  31.     <td><?php print($r['author']); ?></td>
  32.     <td><?php print($r['publish']); ?></td>
  33.    </tr>
  34. <?php
  35.  }
  36. }catch(PDOException $e){
  37.  print($e -> getMessage());
  38.  exit();
  39. }
  40. //データベースを閉じる
  41. $resultset = null;
  42. $pdo = null;
  43. ?>
  44.   </table>
  45.  </body>
  46. </html>

○ 実行結果

実行結果
実行結果

前へ   次へ