PHP实现15题双选项五维度问卷,计数器统计结果遇问题求排查
Hey Dave, let's dig into this questionnaire issue you're facing. Since your code snippet cuts off, I'll walk through the most common pain points with this type of dual-option, multi-dimension survey—stuff that tripped me up when building similar tools too.
1. 数据库查询与数据完整性
Your code starts with $db->pr... which I assume is a prepared statement. Let's check the basics first:
- Verify that
testID = 2maps to a complete dataset in your DB: 15 full questions, each linked to the correctanswerTypeand dimension. It's easy to accidentally delete a row or mislink a question to the wrong dimension. - Double-check your prepared statement syntax: Did you bind
$testIDcorrectly? Are your column names matching the DB (e.g.,answer_typevs.answerType—case sensitivity matters in some databases)? - Dump the query results to confirm you're getting all 15 questions. A misplaced
WHEREclause could be filtering out half your survey without you noticing.
2. Session & User State Handling
You're relying on $_SESSION["currentUser"], so let's rule out session-related bugs:
- Did you add
session_start()at the very top of your script? It's a tiny thing but easy to forget, and it breaks everything if missing. - Confirm the session actually holds valid user data. Do a
var_dump($_SESSION["currentUser"])to make sure the user ID or other critical values aren't missing or corrupted. - If you're saving partial progress, check that you're storing and retrieving answered questions correctly from the session—overwriting existing data is a common mistake here.
3. AnswerType & Dimension Mapping Logic
This is where most dual-option survey bugs hide, since the link between "agree/disagree" and your 5 opposing dimensions is entirely custom:
- Map out each question manually: Does selecting "agree" for question 1 really correspond to "extrovert" (or whatever your dimension is), and "disagree" to "introvert"? It's shockingly easy to flip these mappings for a single question and throw off the whole result.
- Check your scoring logic: Are you correctly aggregating scores per dimension? For example, if 3 questions belong to the "thinking" dimension, are you adding their values together without mixing in scores from other dimensions?
- Add a sanity check: Make sure every question's
answerTypeis tied to one of your 5 defined dimensions. A strayanswerTypethat doesn't map to anything will break your final dimension calculations.
4. Frontend Form & Submission Issues
Don't overlook the frontend—even if your PHP is solid, bad form markup can break everything:
- Verify your radio button
nameattributes: Each question should have a unique name (likeq1,q2) or use an array format (questions[]) so PHP can correctly parse the submitted answers. - Check the
valueof each option: Does "agree" map to the exactanswerTypevalue your backend expects? For example, if your DB usesextrovertas the value, your radio button should havevalue="extrovert", not a random string. - Add basic frontend validation: If a user skips a question, does your backend handle the missing value gracefully? Undefined variables from missing answers can crash your scoring logic.
5. Compare to Your Working Old Code
Since you've built this before, this is the fastest way to spot issues:
- Line up the database query sections: Did you change table names, join logic, or selected columns in the new code?
- Compare the dimension scoring function: How did your old code map
answerTypeto dimension scores? Did you tweak the logic in the new version and miss a step? - Check session handling differences: Did your old code have special logic for initializing sessions or storing user data that you didn't replicate?
Quick Example of a Solid Base (for reference)
Here's a trimmed-down version of how I've built similar surveys before, to give you a baseline:
session_start(); if (isset($_SESSION["currentUser"])) { $testID = 2; // Fetch questions with proper prepared statement $stmt = $db->prepare("SELECT id, question_text, agree_type, disagree_type, dimension FROM survey_questions WHERE test_id = ?"); $stmt->bind_param("i", $testID); $stmt->execute(); $result = $stmt->get_result(); $questions = $result->fetch_all(MYSQLI_ASSOC); $stmt->close(); // Handle form submission if ($_SERVER["REQUEST_METHOD"] === "POST") { $userAnswers = $_POST['questions']; $dimensionScores = [ 'thinking' => 0, 'energy' => 0, 'nature' => 0, 'tactics' => 0, 'identity' => 0 ]; // Calculate scores per dimension foreach ($questions as $q) { $selectedAnswer = $userAnswers[$q['id']]; if ($selectedAnswer === 'agree') { $dimensionScores[$q['dimension']] += 1; // Adjust scoring value as needed } else { $dimensionScores[$q['dimension']] -= 1; } } // Save results to DB $userId = $_SESSION["currentUser"]['id']; $scoresJson = json_encode($dimensionScores); $stmt = $db->prepare("INSERT INTO survey_results (user_id, test_id, dimension_scores) VALUES (?, ?, ?)"); $stmt->bind_param("iis", $userId, $testID, $scoresJson); $stmt->execute(); $stmt->close(); } } else { header("Location: login.php"); exit; }
内容的提问来源于stack exchange,提问作者Dave Farquhar

