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
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. :)
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));
}
}