0

I have a simple table "Exams" with the columns id, title and a form with a variable amount of exam input fields.

But when one submit the form the last value will be saved triple times.

I suppose it's because of the $sql_insert statement with the same value.

How can i change the code that the different values are submitted in that $sql_insert statement?

echo '<form action="" method="post">';
    for ($i = 1; $i <= $student['passed_exams']; ++$i) {
        echo '<label>Exams '.$i.' :</label>';
        echo '<input type="text" id="id['.$i.']" name="title" placeholder="passed Exam" />';
        echo '<br />';
    }
echo '<input type="submit" value=" Submit " name="submit" /></form>';

if (isset($_POST['submit'])) {
    for ($i = 0; $i < $student['passed_exams']; ++$i) {
      $sql_insert = "INSERT INTO exams (title) VALUES ('".$_POST['title']."')";
      $dbConnection->query($sql_insert);
    }
    $dbConnection->close();
}

2 Answers 2

2

Php needs name as an array

echo '<form action="" method="post">';
    for ($i = 1; $i <= $student['passed_exams']; ++$i) {
        echo '<label>Exams '.$i.' :</label>';
        echo '<input type="text" id="id['.$i.']" name="title['.$i.']" placeholder="passed Exam" />';
        echo '<br />';
    }
echo '<input type="submit" value=" Submit " name="submit" /></form>';

if (isset($_POST['submit'])) {
    for ($i = 0; $i < $student['passed_exams']; ++$i) {
      $sql_insert = "INSERT INTO exams (title) VALUES ('".$_POST['title'][$i]."')";
      $dbConnection->query($sql_insert);
    }
    $dbConnection->close();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to make the title array first as

 name="title['.$id.']"

Then you have to save it as

$_POST['title'][$id]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.