Multiple radio button array for php form

后端 未结 2 1140
生来不讨喜
生来不讨喜 2020-12-10 09:56

I\'m new to this. I\'m studying web development and have to create a php response form for a questionnaire which then inputs into a database. I\'m having trouble with the ra

2条回答
  •  独厮守ぢ
    2020-12-10 10:25

    When you're unsure of how to handle the HTML markup that you've set up, you should var_dump($_POST) the values that are sent to the PHP handler page so you know what the format will look like, that way you can proceed from there.

    When I created your HTML and tested it with a var_dump and some random selections, the output was

    array(2) { ["answer"]=> array(3) { [1]=> string(1) "5" [2]=> string(1) "3" [3]=> string(1) "4" } ["submit"]=> string(6) "Submit" }
    

    Notice that there is an array within the $_POST['answer'] variable. So you should foreach over each element in that array to handle each respective value:

    foreach ($_POST['answer'] as $answer) {
        // do stuff with the answer
    }
    

    If you need to work with the answer number that you defined in the POST array, you can foreach with a key:

    foreach ($_POST['answer'] as $answerNum => $answer) {
        // do stuff with $answerNum and $answer
    }
    

    You can, of course, access your answer by its number directly:

    if (!empty($_POST['answer'][1])) { // To ensure that the value is being sent
        // do stuff with $_POST['answer'][1]
    }
    

提交回复
热议问题