2017-08-16 20 views
1

我有這樣一段代碼:按鈕表使用PHP/SQL循環

<?php $res = $conn->query("SELECT * FROM users"); 
    //If the result of the query has more than 0 rows (1 or more) continue to the loop 
    if(mysqli_num_rows($res) >0){ 
     //Loop to organise the data 
     while($row = mysqli_fetch_array($res)){ 
      if($row['permission'] == "2"){ 
       $perms = '<span class="label label-danger">Administrator</span>'; 
      } elseif($row['permission'] == "1"){ 
       $perms = '<span class="label label-success">Registered User</span>'; 
      } else { 
       $perms = '<span class="label label-warning">Awaiting Approval</span>'; 
      } 


      //Return the table data 
      echo "<tr><td>" . $row['firstname'] . "</td><td>" . $row['surname'] . "</td><td>" . $row['email'] . "</td><td>" . $row['username'] . "</td><td>" . $row['telephone'] . "</td><td>" . $perms . "</td>"; 

     } 
    }?> 

我要的是在新列中添加一個按鈕,每一行,將激活一段代碼刪除記錄在數據庫中。

http://i.imgur.com/IilGIKi.png

想知道如果有人可以幫助或點我就如何做到這一點的正確方向。最終會出現一個刪除按鈕和一個批准按鈕,用於激活位於同一文件中的不同SQL代碼。 謝謝

回答

1

你可以這樣做: 插入一個按鈕,它會發送一個變量「delete_id」與當前的「用戶ID」從數據庫中。

在代碼的頂部,你發現如果是刪除,如果它是通過郵寄的形式給出一個動作......

這是不是很安全,但我會增加一些安全性檢查,如:是數?是有效的用戶ID? referal頁面是什麼? ...

<?php 
if ($_POST["delete_id"]) { 
    // This action will be performed after click on the Delete button. 
    // Better make some security checks here 
    $delete_id = htmlspecialchars($_POST["delete_id"]); 
    $res = $conn->query("DELETE FROM `users` WHERE `id` = '$delete_id' LIMIT 1;"); 
} 

$res = $conn->query("SELECT * FROM users"); 
//If the result of the query has more than 0 rows (1 or more) continue to the loop 
if(mysqli_num_rows($res) >0){ 
    //Loop to organise the data 
    while($row = mysqli_fetch_array($res)){ 
     if($row['permission'] == "2"){ 
      $perms = '<span class="label label-danger">Administrator</span>'; 
     } elseif($row['permission'] == "1"){ 
      $perms = '<span class="label label-success">Registered User</span>'; 
     } else { 
      $perms = '<span class="label label-warning">Awaiting Approval</span>'; 
     } 
     // Creates a button with POST variable "delete_id" and the value of the "user id" 
     $button = '<form method="post" action="' . $_SERVER["PHP_SELF"] . '"><input type="hidden" name="delete_id" value="' . $row['id'] . '"><input type="submit" value="Delete this row"></form>'; 


     //Return the table data 
     echo "<tr><td>" . $row['firstname'] . "</td><td>" . $row['surname'] . "</td><td>" . $row['email'] . "</td><td>" . $row['username'] . "</td><td>" . $row['telephone'] . "</td><td>" . $perms . "</td><td>" . $button . "</td>"; 
    } 
} 
?> 
+0

感謝您的回覆,我編輯了代碼以添加您建議的內容。但是,我無法點擊按鈕,它們顯示出來,但不允許我點擊它們來執行代碼。有任何想法嗎? –