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

时间:2015-07-20 09:55:39

标签: php arrays loops session-variables

我试图将变量$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

我在每个BTW文件的顶部使用session_start();

2 个答案:

答案 0 :(得分:2)

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

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

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

(或者,新风格,从PHP 5.4开始)

$_SESSION['candid'] = [];

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

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

你可以在editor.php。

中迭代数组

答案 1 :(得分:1)

您可以通过将{]添加到$_SESSION['clientid']来实现您想要的效果:$_SESSION['clientid'][]这基本上意味着&#34;将其附加到数组&#34;。