php insert multiple values into separate rows in mysql table

后端 未结 2 1658
失恋的感觉
失恋的感觉 2020-12-22 11:30

I have a PHP form with various types of input fields (checkbox, drop-down, radio, auto-complete, etc.) What I would like to do is get users input(which might be more than on

相关标签:
2条回答
  • 2020-12-22 11:37

    The id for the question can be array at the backend side. You can iterate over the array and insert questions in loop.

    The other way is to compose the variable names in for loop by using variable variables.

    Array seems like a cleaner code to me. :)

    0 讨论(0)
  • 2020-12-22 11:39

    If you've already got the answers stored in $_POST by qId, and you're using [] in your input names, as Aret suggests, you could do something like:

    // creates an object, $stmt, which will do an insert whenever $stmt->execute()
    // is called
    $stmt = $conn->prepare('INSERT INTO Answer (qId, answer) VALUES (:qId, :answer)');
    
    $sql="select qId from Answer"; 
    $result = mysql_query($sql) or die(mysql_error());
    
    // loop over all question ids
    while( $row = mysql_fetch_assoc( $result ) ) {
    
      $qId = $row['qId'];
    
      // loop over all the answers for one question
      foreach ($_POST[$qId] as $answer) {
    
        // this runs the sql from the first line with :qId set to $qId, 
        // and :answer set to $answer
        $stmt->execute(array(':qId' => $qId, ':answer' => $answer));
    
      }
    
    } 
    
    0 讨论(0)
提交回复
热议问题