当我不调用取消设置它的href时,为什么我的会话变量未设置

问题描述:

In my PHP program I have a few links that all link to the same page. What it does is update the current site depending on my action and I send new information through a GET or if I need to unset my session.

In one link to the same page, I am calling unset($_SESSION['search']) and in the other I am calling a GET for sorting information. But when I call the GET link and not the unset link, my session variable gets reset anyways.

Everything is being done in view.php

Here is my unset link

<a href="view.php<?php unset($_SESSION['search']); ?>">View All</a>

My GET link(s)

<th><a href="view.php?id=<?php echo 'id';?>">ID</a></th>

<th><a href="view.php?id=<?php echo 'itemName';?>">Item Name</a></th>

<th><a href="view.php?id=<?php echo 'description';?>">Description</a></th>

<th><a href="view.php?id=<?php echo 'supplierCode';?>">Supplier</a></th>

<th><a href="view.php?id=<?php echo 'cost';?>">Cost</a></th>

When I call the unset link, I need it to reset the session variable. But when I call the get links, I need to keep the session variable.

What can I do to make that happen?

My php action when calling those links

if (isset($_SESSION['search'])) {

    $sql_query = "SELECT * FROM inventory WHERE description LIKE '%".$_SESSION['search']."%' ORDER BY ".$id." ASC";

    $check = true;
}


else if ($_POST && !(Trim($_POST['search']) === '')) {

    $search = $link->real_escape_string($_POST['search']);

    $_SESSION['search'] = $search;

    $sql_query = "SELECT * FROM inventory WHERE description LIKE '%".$_SESSION['search']."%' ORDER BY ".$id." ASC";

    $check = true;
}

else {
    $sql_query = "SELECT * FROM inventory ORDER BY ".$id." ASC";

}

Because the $_SESSION['search'] is always reset whenever I redirect back to view.php, the last else is always called when I press the get links even though I need it to stay!

Your unset link structure appears to just be calling unset() on the "search" variable inline, within the href of the "View All" link. That would make it unset "search" no matter what. It seems like something like this could work for you:

<a href="view.php?unset=1">View All</a>

And then in your php action:

if ($_GET['unset'] == 1) {
        unset($_SESSION['search']);
}
if (isset($_SESSION['search'])) {
        $sql_query = "SELECT * FROM inventory WHERE description LIKE '%".$_SESSION['search']."%' ORDER BY ".$id." ASC";
        $check = true;
}