"select * from テーブル where 条件"
select * from sampletable where name = 'taro'こんな具合にすればいいわけですね。では、先ほどのindex.phpを改良して、名前を検索し表示するようにしてみましょう。(下のリストを参照)
where name like 'yamada*'例えば、where句をこのようにすると、nameの値が「yamada」で始まるものがすべて検索されます。"yamada taro"も、"yamadasan"も、yamadaではじまるものはすべて検索できます。
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
<?php
$result = "";
$query = "select * from sampletable";
if (isset($_POST['name'])){
$fstr = $_POST['name'];
if ($fstr != ''){
$query .= " where name = '$fstr'";
}
}
try {
$pdo = new PDO("mysql:host=localhost;dbname=mysampledata;charset=utf8",
"root","");
$statement = $pdo->query($query);
while($record = $statement->fetch(PDO::FETCH_ASSOC)){
$result .= "<tr>";
foreach($record as $column){
$result .= "<td>" . $column . "</td>";
}
$result .= "</tr>";
}
} catch(PDOException $e){
$result = "#ERR:" . $e->getMessage();
}
$pdo = null;
?>
<!doctype html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" />
<title>sample page</title>
<style>
h1 { font-size:14pt;
padding:5px;
background-color:#AAFFFF; }
table tr td {
padding:5px;
background-color:#DDFFCC; }
</style>
</head>
<body>
<h1>Hello PHP!</h1>
<table>
<form method="post" action="./index.php">
<tr><td>検索テキスト:</td><td><input type="text" name="name"></td></tr>
<tr><td></td><td><input type="submit" value="送信"></td></tr>
</form>
</table>
<hr>
<table>
<?php echo $result; ?>
</table>
</body>
</html>
| << 前へ | 次へ >> |