2013-11-25 73 views
0

我有一個問題,我不知道如何解決它。 我有一段時間爲表格中的每一行創建一個表單。現在我想編輯一個字段,並使用字段中的數據更改數據庫中的數據。雖然輸入字段PHP - > DB

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(); 
    } 
} 

問題是我不知道如何使name =「grade」獨特,並在ifset中使用它。當然,我可以改變name =「$ result [id]」,但是我不知道如何在isset中使用($ _ POST ['$ result ['id'])。

謝謝

+1

小心...用'用htmlspecialchars()'圍繞HTML的情況下使用任意的數據,以確保您生成有效的HTML和防止XSS攻擊。 – Brad

+0

謝謝......我將更改我的代碼 – Comy

+0

您正試圖使這一個功能處理所有事情。不要這樣做。構建表單的一個功能。一個函數來處理更新。還有一個功能是把它們放在一起,在黑暗中把它們綁在一起。 –

回答

1

執行以下操作可能會幫助,

簡單地傳遞等級ID作爲隱藏字段的表單,

echo "<input type='hidden' name='id' value='$result[id]'>"; 

,並同時更新

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']) 
0

試試這個

echo "<input type='text' name=".(isset($_POST[$result['id'])?$_POST[$result['id']):"grade")."value='$result[grade]'>"; 

或者更好:

$tGrade = isset($_POST[$result['id'])? $_POST[$result['id']):"grade"; 
echo "<input type='text' name=".$tGrade."value='$result[grade]'>";