2017-05-04 69 views
0

我的問題是如何在頁面用戶列表上的刪除按鈕上單擊操作後,將GET方法更改爲POST方法。從數據庫中刪除用戶 - 將GET方法更改爲POST方法

在頁面頂部使用POST刪除後,users.php必須爲「User $ name deleted!」消息。

users.php

<!DOCTYPE html> 

<html> 
<head> 
    <meta charset="UTF-8"/> 
    <title>Users</title> 
</head> 

<body> 
<h1>Users List</h1> 

<?php 
include('db_connect.php'); 

$db_conn = @new mysqli($host, $db_user, $db_password, $db_name); 


if($result=$db_conn->query("SELECT * FROM user ORDER BY id")){ 
    if($result->num_rows > 0){ 


     echo "<table border='1' cellpadding='10'>"; 
     echo "<tr><th>ID</th><th>Name</th></tr>"; 


     while($row=$result->fetch_object()){ 
      echo "<tr>"; 
      echo "<td>".$row->id."</td>"; 
      echo "<td>".$row->name."</td>"; 
      echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>"; 
      echo "</tr>"; 
     } 

     echo "</table>"; 

    }else{ 
     echo "No records"; 
    } 
}else{ 
    echo "error: ". $db_conn->error; 
} 

$db_conn->close(); 

?> 

<br><a href="add.php">Add user</a> 

</body> 
</html> 

delete.php

<?php 

require_once 'db_connect.php'; 


$db_conn = @new mysqli($host, $db_user, $db_password, $db_name); 

if (isset($_GET['id']) && is_numeric($_GET['id'])) 
{ 

    $id = $_GET['id']; 


    if ($stmt = $db_conn->prepare("DELETE FROM user WHERE id = ? LIMIT 1")) 
    { 
     $stmt->bind_param("i",$id); 
     $stmt->execute(); 
     $stmt->close(); 
    } 
    else 
    { 
     echo "ERROR: could not prepare SQL statement."; 
    } 
    $db_conn->close(); 


    header("Location: users.php"); 
} 
else 

{ 
    header("Location: users.php"); 
} 

請幫幫忙! :)

+0

您爲什麼需要使用後? – Chinito

+0

我的活動是這樣做的 –

+1

你將不得不創建一個表格或使用AJAX的 –

回答

1

使用form與嗨dden輸入&提交按鈕,而不是鏈接:

變化:

 echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>"; 

有了:

變化:

if (isset($_GET['id']) && is_numeric($_GET['id'])) 
{ 
    $id = $_GET['id']; 

 echo '<td><form action="delete.php" method="POST"><input type="hidden" name="id" value="' . $row->id . '"><input type="submit" name="submit" value="Delete"></form></td>'; 

&想必這應該在PHP處理

收件人:

if (isset($_POST['id']) && is_numeric($_POST['id'])) 
{ 
    $id = $_POST['id']; 
+0

它的作品:)謝謝:) 現在刪除後,我必須有網站頂部的信息user.php「用戶$用戶名刪除!」 我可以做到這一點,但刷新後的消息存在 也許ssesions或嘗試cath –

+0

很高興知道它的作品。你可以這樣做:如果POST請求刪除了元素,你可以用GET參數重定向到delete.php。 – Hossam

0

你可以做那麼

下在你delete.php

if($_SERVER['REQUEST_METHOD'] == 'POST') 
{ 
    //DO the deletin here 
} 

在users.php

echo "<td><form action='delete.php' method = 'post'><input type = 'hidden' name = 'user_id' value = '" . $row->id . "' /><button type = 'submit'> Delete</button></form></td>"; 
相關問題