从数据库中删除用户 - GET方法更改为POST方法

时间:2017-05-04 10:21:59

标签: php mysql post get

我的问题是如何在用户列表页面上的删除按钮上单击操作后将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");
}

请帮忙! :)

2 个答案:

答案 0 :(得分:2)

使用隐藏输入的form&amp;提交按钮而不是链接:

变化:

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

使用:

        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($_GET['id']) && is_numeric($_GET['id']))
{
    $id = $_GET['id'];

致:

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

答案 1 :(得分: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>";