表单提交以在PHP中更改/修改会话变量

时间:2013-11-14 20:27:24

标签: php forms session submit

在顶部我有一个会话开始,会话ID可以在所有网页上传递,因为ID在所有网页上都是相同的,这还包括一个名为'username'的会话变量,其值为Guest。 我想将此变量更改为在表单中输入的变量。 这是我的第一篇文章,对于任何错误都很抱歉。

<form class="form1" method="post" action="./" id="form1">
<fieldset>
    <ul>
            <p>Please enter your username to continue to the webshop.</p>
            <label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name" class="required" role="input" aria-required="true"/></span>

            <input  class="submit .transparentButton" value="Next" type="submit" name="Submit"/> 

    </ul>
    <br/>
    </fieldset>
</form>

<?
if (isset($_POST['Submit'])) {
     $_SESSION['username'] = $_POST['username'];
}
?> 

由于

1 个答案:

答案 0 :(得分:4)

你需要在./引号中取出action="",如下所示(这是因为你使用相同的文件处理表单)...并始终用{开始你的php开场{1}}

<?php

如果你想测试它尝试这样的事情:

<form class="form1" method="post" action="" id="form1">
<fieldset>
    <ul>
            <p>Please enter your username to continue to the webshop.</p>
            <label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name" class="required" role="input" aria-required="true"/></span>

            <input  class="submit .transparentButton" value="Next" type="submit" name="Submit"/> 

    </ul>
    <br/>
    </fieldset>
</form>

<?php
if (isset($_POST['Submit'])) {
     $_SESSION['username'] = $_POST['username'];
}
?> 

在进行更改后测试代码,它工作正常......看:

  

Tested screenshot


根据评论中的请求更新答案

<?php
if (isset($_POST['Submit'])) {
    $_SESSION['username'] = $_POST['username'];

    // Use the following code to print out the variables.
    echo 'Session: '.$_SESSION['username'];
    echo '<br>';
    echo 'POST: '.$_POST['username'];
}
?> 

将它放在你的index.php

<form class="form1" method="post" action="./" id="form1">
    <fieldset>
       <ul>
            <p>Please enter your username to continue to the webshop.</p>
            <label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name" class="required" role="input" aria-required="true"/></span>

            <input  class="submit .transparentButton" value="Next" type="submit" name="Submit"/> 

       </ul>
       <br/>
    </fieldset>
</form>