<!doctype html> <html> <head> <title>検索画面</title> <meta charset="utf-8"> </head> <body> <h1>検索画面</h1> <form action="pdo_search.php" method="post"> 検索用語を入力:<input type="text" name="yourname"> <input type="submit" value="検索する"> </form> </body> </html>
mysqlのテーブルからfetch
<?php header("Content-type: text/html; charset=utf-8"); if(empty($_POST)){ header("Location: pdo_search_form.html"); exit(); } else { //名前入力判定 if(!isset($_POST['yourname']) || $_POST['yourname'] === ""){ $errors['name'] = "名前が入力されていません。"; } } if(count($errors) === 0){ $dsn = 'mysql:host=localhost;dbname=test;charset=utf8'; $user = 'dbuser'; $password = 'xxxx'; try { $dbh = new PDO($dsn, $user, $password); $statement = $dbh->prepare("select * from rss where title LIKE (:title)"); if($statement){ $yourname = $_POST['yourname']; $like_yourname = "%".$yourname."%"; //プレースホルダへ実際の値を設定 $statement->bindValue(':title',$like_yourname, PDO::PARAM_STR); if($statement->execute()){ //レコード件数取得 $row_count = $statement->rowCount(); while($row = $statement->fetch()){ $rows[] = $row; } } else { $errors['error'] = "検索失敗しました。"; } $dbh = null; } }catch (PDOException $e){ print('Error:'.$e->getMessage()); $errors['error'] = "データベース接続失敗しました。"; } } ?> <!doctype html> <html> <head> <title>検索結果</title> <meta charset="utf-8"> </head> <body> <?php if (count($errors) === 0): ?> <p><?=htmlspecialchars($yourname, ENT_QUOTES, 'utf-8')."さんで検索しました。"?></p> <p><?=$row_count?>件です。</p> <table border='1'> <tr><td>id</td><td>title</td></tr> <?php foreach($rows as $row){ ?> <tr> <td><?=$row['id']?></td> <td><?=htmlspecialchars($row['title'],ENT_QUOTES,'utf-8')?></td> </tr> <?php } ?> <?php elseif(count($errors) > 0): ?> <?php foreach($errors as $value){ echo "<p>".$value."</p>"; } ?> <?php endif; ?> </body> </html>