PHP获取单选按钮值问题求助:匿名选择表单失效
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
$idwithout ensuring it's defined—this will throw an error if$idhasn't been initialized elsewhere. - It's good practice to add a fallback case in case the
anonymvalue 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

