如何在 PHP 页之间的循环中传递 SESSION 变量

How to pass a SESSION variable within a loop between PHP pages

我正在尝试将变量 $candid$clientid 从 active.php 传递到 editor.php。这是我目前为 active.php:

编写的代码
$active_tsquery = db_select("SELECT * FROM timesheets WHERE status=\"cand\" OR status=\"client\" ORDER BY weekending ASC"); 
    echo "<table width=\"90%\">
        <tr>
        <td width=\"20%\">Client Company</td>
        <td width=\"20%\">Candidate</td>
        <td width=\"20%\">Week Ending</td>
        <td width=\"20%\">Action</td>
        </tr>";

    foreach($active_tsquery as $key => $value) {
        $clientid = $value["clientid"];
        $_SESSION['clientid'] = $clientid;
        $weekend = $value["weekending"];
        $clientresult = db_select("SELECT * FROM timesheetlogin WHERE id=\"$clientid\"");
        $candid = $value["candid"];
        $_SESSION['candid'] = $candid;
        $candresult = db_select("SELECT * FROM timesheetlogin WHERE id=\"$candid\"");
        $ts_id = $value["ts_id"];
        $_SESSION['tsid'] = $ts_id;

        foreach ($clientresult as $key => $value) {
            $company = $value["company"];
        }
        foreach ($candresult as $key => $value) {
            $candidate = $value["name"];
        }

        echo "<tr><td class=\"main-text\">$company</td><td class=\"main-text\">
$candidate</td><td class=\"main-text\">$weekend</td><td class=\"main-text\">
<a href=\"editor.php?id=$ts_id\" class=\"main-link\">Edit</a></td><td class=\"main-link\">
<a href=\"deleteconfirm.php?id=$ts_id\" class=\"main-link\">Delete</a></td></tr>";
    } 

Active.php 正在工作,因为 <a href=\"editor.php?id=$ts_id\" class=\"main-link\">Edit</a> 提供了正确的网址。

这是我在 editor.php:

中的代码
$candid = $_SESSION['candid'];
$clientid = $_SESSION['clientid'];
$candresult = db_select("SELECT * FROM timesheetlogin WHERE id=\"$candid\"");
$clientresult = db_select("SELECT * FROM timesheetlogin WHERE id=\"$clientid\"");
$tsresult = db_select("SELECT * FROM timesheets WHERE candid=\"$candid\"");
var_dump($tsresult);

var_dump($tsresult);为1的数组,每次返回最后一个时间表。我假设是因为 $candid 是错误的。 active.php 中的 foreach 循环已完成并且 $candid 正在从数组中的最后一项返回?

顺便说一句,我在每个文件的顶部使用 session_start();

在 foreach 循环的每次迭代中,您覆盖 $_SESSION['candid'] 的当前值。这就是为什么只有最后一个 candid 出现在 editor.php.

中的原因

PHP 支持会话变量中的数组,因此如果在 foreach 循环之前初始化数组:

$_SESSION['candid'] = array();

(或者,新样式,从 PHP 5.4 开始工作)

$_SESSION['candid'] = [];

并将 candid 添加到循环内的数组中:

$_SESSION['candid'][] = $candid;

您可以遍历 editor.php 中的数组。

您可以通过将 [] 添加到 $_SESSION['clientid'] 来实现您想要的效果,如下所示:$_SESSION['clientid'][] 本质上意味着 "append this to the array".