You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP获取单选按钮值问题求助:匿名选择表单失效

Fixing Your Anonymous Radio Button Form Issue

Hey there! Let's get your anonymous selection form working properly. I notice a couple of key issues in your code that are likely causing the problem—let's break them down and fix them step by step.

1. Missing HTML Form Wrapper

Your radio buttons aren't wrapped inside a <form> element with the correct method, which means the form data won't be sent via POST to your PHP script. Without this, $_POST['anonym'] will never be set!

Corrected HTML Code

<form method="post" action="">
  <input type="radio" name="anonym" value="ja" />Ja
  <input type="radio" name="anonym" value="nei" checked/>Nei
  <!-- Don't forget the submit button with the correct name! -->
  <button type="submit" name="snd_skjema">Submit</button>
</form>

2. PHP Code Improvements

There are a couple of potential pitfalls in your PHP logic:

  • You're using $id without ensuring it's defined—this will throw an error if $id hasn't been initialized elsewhere.
  • It's good practice to add a fallback case in case the anonym value isn't set (even though you have a default checked radio, edge cases can happen).

Corrected PHP Code

if (isset($_POST['snd_skjema'])) {
    // First, make sure $id is defined (replace with your actual user ID logic)
    $id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null; // Example using session
    
    // Check if the 'anonym' value exists before using it
    if (isset($_POST['anonym'])) {
        if ($_POST['anonym'] == 'ja') {
            $anonym = $id; // Only assign if $id is valid
        } elseif ($_POST['anonym'] == 'nei') {
            $anonym = null;
        }
    } else {
        // Fallback in case no option was selected (though your default should prevent this)
        $anonym = null;
    }

    // Optional: Debug to see what values you're getting
    var_dump($_POST);
    var_dump($anonym);
}

Quick Debug Tip

If it's still not working, add var_dump($_POST); right at the start of your PHP script. This will show you exactly what data is being sent from the form—if anonym isn't in the output, double-check your form's method and the radio button names.

内容的提问来源于stack exchange,提问作者Lowtexx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:43:04