小さい頃はエラ呼吸

いつのまにやら肺で呼吸をしています。


PHP5.3とSQLite3でつくる検索フォームのサンプルアプリ

はじめに

PHP5.3とSQLite3を使って、Web画面からSQLite3に格納されているデータを検索するフォームを作ってみました。
前回までのエントリは、こちら。

検索画面のHTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<fieldset>
<legend>検索フォーム</legend>
<form id="frmSearch" action="search.php" method="POST">
<input type="text" id="keyword" name="keyword" 
  value="<?php print htmlspecialchars($_POST["keyword"]); ?>">
<input type="submit" id="search" value="search">
</fieldset>
</form>
<hr>
<?php
//ここにPHPスクリプトを埋め込む
?>
</body>
</html>
検索処理を行うPHPスクリプト
<?php
  // DBへの接続
  try {
    $db = new SQLite3('hoge.db');
  } catch (Exception $e) {
    print 'DBへの接続でエラーが発生しました。<br>';
    print $e->getTraceAsString();
    return;
  }
  
  // リクエストからデータを取得
  $keyword = $_POST["keyword"];
  $keyword = $db->escapeString($keyword);
  
  // リクエストデータが存在しない場合は、すべて表示する
  if (!$keyword) {
    $sql = "SELECT * FROM hoge";
  }
  else {
    $sql = "SELECT * FROM hoge WHERE name = '" . $keyword . "';";
  }
  
  // SQLの実行
  try {
    $results = $db->query($sql);
  } catch (Exception $e) {
    print 'SQLの実行でエラーが発生しました。<br>';
    print $e->getTraceAsString();
    return;
  }
  
  // 検索結果の表示
  $html = "<table border='1'>";
  while ($row = $results->fetchArray()) {
    $id = $row['id'];
    $name = $row['name'];
    $html = $html . "<tr><td>" . htmlspecialchars($id) . "</td>";
    $html = $html . "<td>" . htmlspecialchars($name) . "</td></tr>";
  }
  $html = $html . "</table>";
  print $html;
  
  // DBとの接続をクローズ
  $db->close();
?>
ポイント