Reputation: 85
I don't really know the best way to word this so I'll try my best to describe what I'm trying to achieve. I have a table within a form like so
<form action="manager-match-report-run.php" method="post" autocomplete="off" name="registerForm">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Goals</th>
<th>Assists</th>
<th>Match Rating</th>
<th hidden>playerId</th>
</tr>
</thead>
<tbody>
<?php
$sql_players = "SELECT * FROM Player WHERE teamId = '$teamId' AND selected = '1'";
$res_players = mysqli_query($conn, $sql_players);
while($row_players = $res_players->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row_players["firstName"]. "</td>";
echo "<td>" . $row_players["lastName"]. "</td>";
echo "<td><div class='form-group'><input name='goals' class='form-control py-4' type='number'/></div></td>";
echo "<td><div class='form-group'><input name='assists' class='form-control py-4' type='number'/></div></td>";
echo "<td><div class='form-group'><input name='matchRating' class='form-control py-4' type='number' step='0.01' min='0' max='10'/></div></td>"
?>
<td hidden><input name="playerId" value="<?php echo $row_players['playerId'];?>"></td>
<?php echo "</tr>";
}?>
</tbody>
</table>
</div>
<div class="form-group mt-4 mb-0"><button id="manager-report-btn" onclick="return confirmReport()" class="btn btn-primary btn-block" type="submit" name="manager-report">Confirm Report</button></div>
</form>
I'm looking for the correct way to insert the data into the correct rows in the Player table. e.g. Update the Player table so Alison has 5 goals, 1 assist, 8 match rating, Ben has 0 goals, 1 assist, 7 match rating etc.
I'm assuming I'd have to use a loop of some sorts but have had no luck so far so any help or advice would be great, thank you :)
Upvotes: 0
Views: 315
Reputation: 913
Your inputs all have the same name, so only the last value gets posted to your app.
Add a dynamic name for each control, for example instead of name='matchRating'
, use
$playerName = htmlentities($playername);
$inputname = sprintf("matchRating[%s]", $playerName);
printf("<input name=\"%s\" type=\"text\"/>", $inputname);
When the form is submitted, you get the data in an array, which you can loop over to update your database records:
$matchRatings = $_GET["matchRating"];
foreach ($matchRatings as $playerName => $rating) {
// Update player rating in database
// Important: Do not forget to guard against SQL injection!
$sql = sprintf("update MYTABLE set MATCHRATING=%d where PLAYERNAME='%s'", $rating, $playerName);
}
Upvotes: 1