I have a problem and I don't know how to solve it. I have a while that creates a form for every row inside my table. Now I want to edit a field and change the data from the DB with the one from the field.
function Grades($id,$sem){
echo "<h3>Grades - Sem $sem</h3>";
$sth = $this->dbh->prepare("SELECT id, grade, subject, date, sem
FROM grades
WHERE id_student = :id AND
sem = :sem");
$sth->bindParam(":id", $id);
$sth->bindParam(":sem", $sem);
$sth->execute();
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<form action='students.php?change-students' method='post'>";
echo "<br>Subject ".$result['subject']." Grade ".$result['grade']." Date ".$result['date']." Sem ".$result['sem']."<br>";
echo "<input type='text' name='grade' value='$result[grade]'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
}
if (isset($_POST['grade'])) {
echo $_POST['grade'];
$sth = $this->dbh->prepare("UPDATE grades
SET grade = :grade
WHERE id_student = :id AND
sem = :sem");
$sth->bindParam(":grade", $_POST['grade']);
$sth->bindParam(":id", $id);
$sth->bindParam(":sem", $sem);
$sth->execute();
}
}
The problem is that I don't know how to make that name="grade" unique and use it in if isset. Of course I could change name="$result[id]" but I don't know how to use inside isset($_POST['$result['id']).
Thank you
Doing the following might help,
simply pass the grades id as hidden field in your form,
echo "<input type='hidden' name='id' value='$result[id]'>";
and while updating
if (isset($_POST['grade'])) {
$sth = $this->dbh->prepare("UPDATE grades
SET grade = :grade
WHERE id= :id // this will be your hidden post id(i.e. $_POST['id'])
Try this
echo "<input type='text' name=".( isset($_POST[$result['id'])?$_POST[$result['id']):"grade")."value='$result[grade]'>";
Or better:
$tGrade = isset($_POST[$result['id'])? $_POST[$result['id']):"grade";
echo "<input type='text' name=".$tGrade."value='$result[grade]'>";