Reputation: 387
I am making a dynamic PHP form that interacts with a mySQL database for entering the scores of students on different assignments. So far I have successfully connected to the database and accessed the necessary data. The following code displays for each student first, their name, and then an empty text input box where the user enters the score said student earned on the assignment.
<?php if(isset($_POST["beginScoring"]) || isset($_POST['submitScores'])){
$result = $connection->query("SELECT id, firstname, lastname FROM student ORDER BY lastname");
if(!$result)
{
echo "Query Failure";
}
else
{
$foo = array();
$c = 0;
echo "<tr><td>Last Name</td><td>First Name</td><td>Points Earned</td></tr>";
while ($row = $result->fetch_assoc())
{
echo "<tr><td>$row[lastname]</td><td>$row[firstname]</td>";
?>
<td><input type="text" size=8 name="" id="" value=""/></td></tr> <!-- I can maybe use an array to store scores . . . -->
<?php
}
}
?>
The thing I am having issues with is how do I name the text input. Since there are going to be an undetermined amount of text boxes, I can't use a single static name for the input item, right? What would be a good way to name the text boxes so that I can easily access them using the POST array?
Upvotes: 1
Views: 5233
Reputation: 359
Those who commented answered the basic question. Using "varname[]" will get you the solution you want. But I think there's more to this issue.
In some way you will need to know what score corresponds to which student. If you simply used name="score[]", then accessing the $_POST['score'] variable on the backend wouldn't tell you which student the score belonged to. You need a way to know that.
So there are two ways to achieve this.
Method 1 is to use a hidden variable
<input type="hidden" name="student[]" value="<?php echo $row['id']?>" />
<td><input type="text" size=8 name="score[]" id="<?php echo $row['id']?>" value=""/>
and then on the backend you would do something like:
foreach ($_POST['student'] AS $key => $id)
{
$score = $_POST['score'][$key];
// $sql = "INSERT INTO scores (`student`,`score`) VALUES ('$id','$score')";
}
But personally I would handle it without using a hidden. Instead I would do something like this with my HTML:
<td><input type="text" size=8 name="score[<?php echo $row['id']?>]" id="<?php echo $row['id']?>" value=""/>
Note that I'm echoing the student ID into the score[] HTML variable name. Then on the backend I can do this:
foreach ($_POST['score'] AS $id => $score)
{
// $sql = "INSERT INTO scores (`student`,`score`) VALUES ('$id','$score')";
}
Good luck!
Upvotes: 2