Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /* エラーを全て例外に変換する */
- set_error_handler(function ($errno, $errstr, $errfile, $errline) {
- throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
- });
- /**
- * HTML特殊文字をエスケープする関数
- */
- function h($str) {
- return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
- }
- // クエリ変数初期化
- $q = '';
- // フォームからクエリを受け取ったか判定
- if (isset($_REQUEST['q']) && is_string($_REQUEST['q'])) {
- // クエリを $q にセット
- $q = $_REQUEST['q'];
- // 半角スペースなどのASCII制御文字や全角スペースで分割して配列化
- $regex = "/[\\x0-\x20\x7f\xc2\xa0\xe3\x80\x80]++/u";
- $keywords = preg_split($regex, $_REQUEST['q'], -1, PREG_SPLIT_NO_EMPTY);
- } else {
- // 空配列
- $keywords = array();
- }
- try {
- // キーワードが1つ以上あるとき
- if (!empty($keywords)) {
- // DBに接続
- mysql_connect('localhost', 'root', '');
- // DBを選択
- mysql_select_db('mydb') or trigger_error(mysql_error());
- // 文字セットを指定
- mysql_set_charset('utf8');
- // LIKE検索用のパーツを組み立てる
- foreach ($keywords as $keyword) {
- $keyword = mysql_real_escape_string('%' . addcslashes($keyword, '\\_%') . '%');
- $holders[] = "(`name` LIKE '{$keyword}')";
- }
- // SQL文生成
- $sql = 'SELECT * FROM `table` WHERE (' . implode(' AND ', $holders) . ')';
- // クエリ実行
- $result = mysql_query($sql) or trigger_error(mysql_error());
- // 件数をセット
- $count = mysql_num_rows($result);
- // メッセージをセット
- $message = "{$count}件見つかりました";
- }
- } catch (ErrorException $e) {
- // 例外を捕捉してメッセージをセット
- $message = $e->getMessage();
- }
- // ヘッダーを送出
- header('Content-Type: text/html; charset=utf-8');
- ?>
- <!DOCTYPE html>
- <html lang="ja">
- <head>
- <title>名前検索</title>
- <style type="text/css">
- table {
- border: solid 3px black;
- }
- tr, td, th {
- border: solid 1px black;
- padding: 15px;
- }
- </style>
- </head>
- <body>
- <h1>名前検索</h1>
- <form action="" method="get">
- <input type="text" name="q" size="30" value="<?php echo h($q) ?>">
- <input type="submit" value="検索する">
- </form>
- <?php if (isset($message)): ?>
- <hr />
- <h1>検索結果</h1>
- <p><?=$message?></p>
- <?php if (!empty($result) && $count): ?>
- <table>
- <tr>
- <th>id</th>
- <th>name</th>
- </tr>
- <?php while ($book = mysql_fetch_assoc($result)): ?>
- <tr>
- <td><?php echo h($book['id']) ?></td>
- <td><?php echo h($book['name']) ?></td>
- </tr>
- <?php endwhile; ?>
- </table>
- <?php endif; ?>
- <?php endif; ?>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement