CodeLiker
CodeLiker

Reputation: 67

put input type text in an array

I have some text inputs. The inputs are produced from a while loop. Now I want put the values in an array. Like this:

array       values
mark['0']   input1
mark['1']   input2
mark['2']   input3

I tried this but not working.

while($row=mysql_fetch_array($result)){
  <form class="form1" name="form1" method="post">
    <input type="text" name="mark[]"/>
  </form>
}
<form class="form1" name="form1" method="post">
    <button type="submit" name="correction"></submit>
</form>

And then

if(isset($_POST['correction'])){
$grade=0;   
    $mark=$_POST['mark'];
    foreach($mark as $key =>$value ){
        $grade+=$value;
    }   
print $grade;
}

I get these errors:

Notice: Undefined index: mark in C:\xampp\htdocs\virtual_exam\handy_correction.php on line 37

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\virtual_exam\handy_correction.php on line 38

The problem may be caused by two forms which arent connected to each other and if YES, how to joined them? If NO, how to do what i want?

Upvotes: 1

Views: 7845

Answers (3)

Legionar
Legionar

Reputation: 7597

Change your form to this:

<form class="form1" name="form1" method="post">

  <?php
    while ($row = mysql_fetch_array($result)) {
      echo '<input type="text" name="mark[]" />';
    }
  ?>

  <input type="submit" name="correction" value="Submit" />
</form>

And then:

if (isset($_POST['correction'])) {
  $grade = 0;   
  $mark  = $_POST['mark'];

  foreach ($mark as $key => $value) {
    $grade += $value;
  }

  echo $grade;
}

Upvotes: 1

rolfv1
rolfv1

Reputation: 571

What you saying the last paragraph is correct, you are submitting the form1 which contains only the submit button, so mark doesn't exist in the PHP script that handles the POST.

so change the HTML to:

<form class="form1" name="form1" method="post">
<?php
while($row=mysql_fetch_array($result)){
?>
    <input type="text" name="mark[]"/>
<?php
}
?>
    <button type="submit" name="correction"></submit>
</form>

Upvotes: -1

Mike Brant
Mike Brant

Reputation: 71384

You should likely have only 1 form element, not one for every row you are trying to output, and certainly not a separate one for the form submission button.

Your problem is that the actual form you are submitting has only one element in it - the submit button. Thus there are no input fields at all to post.

You should generate your form like this:

<form class="form1" name="form1" method="post">
<?php
while($row=mysql_fetch_array($result)){
?>
    <input type="text" name="mark[]"/>
<?php
}
?>
    <button type="submit" name="correction"></submit>
</form>

Upvotes: 2

Related Questions