checked 屬性<label> 提升可用性(點文字也能選取)<form method="post" action="">
<fieldset>
<legend>選擇方案</legend>
<label><input type="radio" name="plan" value="basic" checked> 基礎方案</label><br>
<label><input type="radio" name="plan" value="pro"> 專業方案</label><br>
<label><input type="radio" name="plan" value="enterprise"> 企業方案</label>
</fieldset>
<button type="submit">送出</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$plan = $_POST['plan'] ?? '';
// 白名單驗證
$allowed = ['basic', 'pro', 'enterprise'];
if (!in_array($plan, $allowed, true)) {
die('非法的方案選擇');
}
echo "你選擇了:$plan";
// 後續處理:寫入資料庫、導向付款頁等
}
?>
<?php
// 假設從資料庫撈取
$plans = $pdo->query("SELECT id, name, price FROM plans WHERE active=1")->fetchAll();
?>
<form method="post">
<?php foreach ($plans as $plan): ?>
<label>
<input type="radio" name="plan_id" value="<?= $plan['id'] ?>">
<?= htmlspecialchars($plan['name']) ?> - $<?= $plan['price'] ?>
</label><br>
<?php endforeach; ?>
<button type="submit">確認</button>
</form>
$_POST['plan'] ?? '' 給預設空值,再驗證是否為空。<input type="radio" name="plan" value="pro" <?= $old==='pro' ? 'checked' : '' ?>>name="plan[]"?原始來源:www.111cn.net