<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP 分類查詢示範</title>
</head>
<body>
<div style="text-align:center">
<form method="post" action="">
<input type="submit" name="sell" value="智慧銷售">
<input type="submit" name="manager" value="經營管理">
<input type="submit" name="serve" value="智慧客服">
<input type="submit" name="newemployee" value="智慧新員工">
<input type="submit" name="development" value="個人發展">
</form>
<?php
// 共用資料庫連線函式
function getConnection() {
$conn = mysqli_connect("localhost", "root", "root", "test");
if (!$conn) die('資料庫連線失敗: ' . mysqli_connect_error());
mysqli_set_charset($conn, "utf8");
return $conn;
}
// 共用查詢顯示函式
function queryAndDisplay($keyword) {
$conn = getConnection();
$sql = "SELECT * FROM ts1 WHERE name LIKE ?";
$stmt = mysqli_prepare($conn, $sql);
$like = "%$keyword%";
mysqli_stmt_bind_param($stmt, "s", $like);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
echo '<table border="1" align="center" style="width:60%">';
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
echo '<td>' . htmlspecialchars($row['id']) . '</td>';
echo '<td>' . htmlspecialchars($row['name']) . '</td>';
echo '<td>' . htmlspecialchars($row['image']) . '</td>';
echo '</tr>';
}
echo '</table>';
mysqli_close($conn);
}
// 處理各分類提交
if (!empty($_POST['sell'])) queryAndDisplay('智慧銷售');
if (!empty($_POST['manager'])) queryAndDisplay('經營管理');
if (!empty($_POST['serve'])) queryAndDisplay('智慧客服');
if (!empty($_POST['newemployee'])) queryAndDisplay('智慧新員工');
if (!empty($_POST['development'])) queryAndDisplay('個人發展');
?>
</div>
</body>
</html>
<?php
echo 'Hello, world!';
?>
將檔案存為 hello.php,配置好 PHP 環境後即可在瀏覽器執行。