在<a> click

时间:2018-06-26 22:10:09

标签: php mysql

I'm trying to make an <a> link which triggers PHP code on the next page. I've tried using $_GET variables to do this but the thing is I also want to remove the variable afterwards, as I automatically link back to the redirected page with header(). There don't seem to be any feasible ways to do this without redirecting the user to one page alone, but the thing is they're expected to be redirected to the page they were on previously. Keeping $_GET variables then cause an endless loop of redirects.

In general, I wish to avoid using $_GET as it could be abused in the context I'm using it in. Any other workarounds would be greatly appreciated, though. Basically I'm just trying to use an <a> link to remove an entry from a MySQL database.

Here's the PHP that handles the variable.

if (isset($_GET['rm'])) # 'rm' contains the uuid of the entry to be deleted.
{
    $uuid = $_GET['rm'];
    unset($_GET['rm']); # Didn't expect this to work, of course it didn't remove the variable from the URL.
    $query = "DELETE FROM posts WHERE uuid = '$uuid'";
    $result = $mysqli->query($query);
    header("Location: " . $_SERVER['REQUEST_URI']);
    exit();
}

EDIT: I realize now that I have wildly complicated my explanation here. The main goal was to make the click of an <a> link trigger PHP code, with a variable specific to the link clicked. (Each link is a delete button on a post, and each post has a UUID)

If there is a way to alternatively trigger javascript code, that would be immensely helpful as well, since I'm looking to use such a method here too. I will likely be making a separate thread asking about this.

2 个答案:

答案 0 :(得分:0)

例如,您可以使用$ _SESSION删除变量

    if (isset($_SESSION['rm'])) # 'rm' contains the uuid of the entry to be deleted.
{
    $uuid = $_SESSION['rm'];
    unset($_SESSION['rm']); # Didn't expect this to work, of course it didn't remove the variable from the URL.
    $query = "DELETE FROM posts WHERE uuid = '$uuid'";
    $result = $mysqli->query($query);
    header("Location: " . $_SERVER['REQUEST_URI']);
    exit();
}

考虑您已经注册了下一个形状的值。

$_SESSION['rm'] = "My value";

答案 1 :(得分:-2)

如果您的目标是重定向到当前页面但删除查询字符串,则可以重定向到header("Location: ?");,本质上就是这样。 (从技术上讲,您正在重定向到一个没有值的查询字符串,而该值与根本没有查询字符串的值完全不同,但是php只会显示$_GET的空数组,该数组实际上是相同的)

我将要提到其他选项,例如$_SERVER中的变量,但是其中许多选项具有各种安全性或与之相关的其他问题。我之所以仅提及这一点,是因为除非必要,否则我不建议使用任何方法。另外,它确实没有比上面更容易的方法。