Jump to content

[SOLVED] Inserting 2 arrays into a database using foreach statement


kizzie

Recommended Posts

I have a form that inserts into a database 2 arrays.But the problem is that it submits to the database twice what is being posted!

This is the form:

 

<form method="post" action="ok.php">

<?php

.....

$sid=$row['id']; //result of a query that gets all the id's in the database

$grade=array(A,B,C,D,E,F);

 

echo "<tr><td><input type='checkbox' name='Names[]' value='$sid' checked/>$sid</td>";

 

echo "<td><select name='grade[]'>

<option value=$grade[0] selected>A</option>

<option value=$grade[1]>B</option>

<option value=$grade[2]>C</option>

<option value=$grade[3]>D</option>

<option value=$grade[4]>E</option>

<option value=$grade[5]>F</option></select></td>

</tr>";

 

<input name="Submit" type="submit" class="subHeader" value="Submit" />

</form>

 

This is d page (ok.php) that inserts the data:

 

<?php

include "db.php";

 

$Grade = $_POST['grade'];

$Reg = $_POST['Names'];

 

foreach ($Reg as $stard)

{

foreach ($Grade as $trad)

{

$query = "INSERT INTO result (regNo, grade) VALUES ('$stard', '$trad')"; $result = mysql_query($query);

}

}

?>

 

This is the result that i get wit different grades inserted twice for each id.

 

  215    C

215  A

445  C

445  A

 

How do i insert a particular grade to an id without also being inserted into another id?

As the case above,215 was supposed to have 'C' while 445 was supposed to have 'A'.Not both having 'C' and 'D'.

<?php
include "db.php";

$grade = $_POST['grade'];
$reg = $_POST['Names'];

foreach ($grade AS $index => $pemhc)
{
$query = "INSERT INTO result (regNo, grade) VALUES ('$reg[$index]', '$pemhc')";
$result = mysql_query($query);
}

?>

 

PS PEMHC = pre school middle school high school & college for grade levels :P

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.