php insert multiple values into separate rows in mysql table

后端 未结 2 1687
失恋的感觉
失恋的感觉 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: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));
    
      }
    
    } 
    

提交回复
热议问题