2017-05-07 31 views
0

問題跟蹤哪些列數據應該進入

所以,我有這個程序,允許用戶編輯在數據庫中的學生信息。當提交按鈕被點擊時,信息進入一個數組,所以我可以輕鬆地遍歷信息並將信息放入數據庫。但是,問題是我不知道如何確定信息進入哪一列。

我目前的方法是通過使用一個變量來跟蹤信息應該進入的列,但這是行不通的。

我是我的html,我將學生信息放入輸入中,以便用戶可以編輯信息。

學生表

studentID | firstname | lastname | teacherID 
1   | Bob  | Roberts | 2 
2   | Rick  | Phil  | 1 

PHP形式

<form action="server/edit/students.php" method="post"> 
       <table> 
        <tr> 
         <th>Student ID</th> 
         <th>Firstname</th> 
         <th>Lastname</th> 
         <th>Teacher ID</th> 
        </tr> 
        <?php 
        // get student info 
        $getStudent = $link->prepare("SELECT * FROM students"); 
        $getStudent->execute(); 
        $getStudent = $getStudent->fetchAll(PDO::FETCH_ASSOC); 
        $value = 0; // counts rows 
        // loop through each student 
        foreach ($getStudent as $student) { 
         $studentID = $student['studentID']; 
         $firstname = $student['firstname']; 
         $lastname = $student['lastname']; 
         $teacherID = $student['teacherID']; 

        ?> 

         <tr> 
          <td> 
           <?php echo $studentID ?> 
          </td> 
          <td> 
           <input type='text' name='student[<?php echo $studentID ?>][firstname]' value='<?php echo $firstname ?>' /> 
          </td> 
          <td> 
           <input type='text' name='student[<?php echo $studentID ?>][lastname]' value='<?php echo $lastname ?>' /> 
          </td> 
          <td> 
           <input type='text' name='student[<?php echo $studentID ?>][teacherID]' value='<?php echo $teacherID ?>' /> 
          </td> 
         </tr> 

         <?php 
          // add to row 
          $value += 1; 

        } 
        ?> 
       </table> 
       <button type="submit" name="update">Update</button> 
      </form> 

PHP代碼進程的表格信息

$counter = 0; // keeps track of number of columns 

// get data and loop through it 
foreach ($_POST['student'] as $id => $data) { 
    foreach ($data as $d) { 
     if($counter > 1) { 
      $counter = 0; 

      update($counter, $link, $id, $d); 
     } else { 
      update($counter, $link, $id, $d); 
     } 
    } 
} 

function update($counter, $link, $id, $d) { 

    if($counter == 0) { 
     $update = $link->prepare("UPDATE students SET firstname = :firstname WHERE studentID = :id"); 
     $update->execute(array(
      "firstname" => $d, 
      "id" => $id 
     )); 

     echo $counter . "<br>"; 

     $counter++; 
    } else if($counter == 1) { 
     $update = $link->prepare("UPDATE students SET lastname = :lastname WHERE studentID = :id"); 
     $update->execute(array(
      "lastname" => $d, 
      "id" => $id 
     )); 

     echo $counter . "<br>"; 

     $counter++; 
    } 

} 

回答

1

問題是因爲您的$ counter變量未作爲參考傳遞。請嘗試以下操作:

function update(&$counter, $link, $id, $d) { 

之前,傳遞的變量總是等於0.當您增加它時,不會保存更改。當您使用&標誌通過引用傳遞時,它會通知PHP更新您最初發送的變量,而不是新副本。

編輯:謝謝鮑勃!

+0

它給了我一個'錯誤,意外'&' –

+1

'&'必須進入函數的定義,而不是在調用。 – Bobface