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

NJD*_*NJD 0 php forms session submit

在顶部,我有一个会话启动,会话 ID 可以在所有网页上传递,因为所有网页上的 ID 都是相同的,这还包括一个名为“用户名”的会话变量,其值为 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'];
}
?> 
Run Code Online (Sandbox Code Playgroud)

谢谢

Ari*_*osh 6

您需要在下面的引号中取出./is action=""(这是因为您使用相同的文件来处理表单)...并始终以以下方式开始您的 php 打开<?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'];
}
?> 
Run Code Online (Sandbox Code Playgroud)

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

<?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'];
}
?> 
Run Code Online (Sandbox Code Playgroud)

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

测试截图


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

<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>
Run Code Online (Sandbox Code Playgroud)

将其放入您的index.php

<?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'];
    }
?> 
Run Code Online (Sandbox Code Playgroud)