在不刷新页面的情况下更改PHP变量

时间:2016-07-31 08:37:45

标签: php ajax

无论如何在页面加载后分配/更改PHP变量?例如,假设我有变量$username$username尚未设置,但是一旦用户提交了一个包含将设置$username的输入字段的表单,就会设置$username。基本上,$username = $_POST["username"];将成为$prevUsername; $newUsername; if ((isset($_POST["username"])) { $newUsername = $_POST["username"]; if ($username == "") { $db->query("INSERT INTO Users (`username`) VALUES ('$newUsername')"); $prevUsername = $newUsername; } else { $db->query("UPDATE Users SET username = '$newUsername' WHERE username = '$prevUsername'"); $prevUsername = $newUsername; } } 假设用户决定再次更改用户名。 (注意:页面永远不会在用户提交时刷新,它是同一页面。)$ username再次分配给$ _POST [“username”]。使用这种当前的方法,它对我不起作用。我构建了以下内容:

session_start();
ob_start();

$_SESSION["username"];
if (isset($_POST["username"]))
{
   if (isset($_SESSION["username"]))
   {
       $db->query("UPDATE Users SET username = '{$_POST['username']}' WHERE username = '{$_SESSION['username']}'");
   }

   else
   {
      $db->query("INSERT INTO Users (`username`) VALUES ('{$_POST['username']}')");
    $_SESSION["username"] = $_POST["username"];
   }
}

当用户提交用户名时,它可以正常工作。只有当用户想要更新用户名时,它才会停止正常工作。更新用户名不会返回任何错误,但不会根据以前的用户名更新。它不像更新那样保持不变,就像UPDATE SQL语句从未启动一样。有没有办法解决这个问题?

使用会话变量:

var app = angular.module('app', []);

    app.value('val','Hi');

    app.config(function ($provide) {
        $provide.decorator('val', function ($delegate) {
            return $delegate + ' Angular!';
        });
    });

1 个答案:

答案 0 :(得分:0)

PHP为stateless,这意味着在请求完成后,服务器内存中没有任何内容。换句话说,PHP无法跟踪var $prevUsername,因为它在请求之间丢失了。你应该做的是将变量存储在更持久的东西中,例如会议:

<?php
    session_start();

    if (isset($_POST['username'])) {
        if (!isset($_SESSION['prevUsername'])) {
            $stmt = $db->prepare('INSERT INTO Users (`username`) VALUES (?)');
            $stmt->bind_param('s', $_POST['username'])
            $stmt->execute();

            $_SESSION['prevUsername'] = $_POST['username'];
        }else{
            $stmt = $db->prepare('UPDATE Users SET username = ? WHERE username = ?');
            $stmt->bind_param('s', $_POST['username'])
            $stmt->bind_param('s', $_SESSION['prevUsername'])

            $_SESSION['prevUsername'] = $_POST['username'];
        }
}

如果你想和ajax一起使用:

<html>
    <head>
        <meta charset="UTF-8" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </head>
    <body>
        <form method="POST">
            <input type="text" id="txt_username" />
            <input type="submit" id="btn_submit" />
        </form>
        <hr />
        <div id="username"></div>
        <div id="output"></div>
        <hr />
        <script>
            $(function() {
                $('#btn_submit').on('click', function(e) {
                    e.preventDefault();
                    request();
                });
                request();
            });
            function request() {
                $.ajax({
                  type: 'POST',
                  url: 'http://www.darkbee.be/stack/username/process.php',
                  data: {'username':$('#txt_username').val(),},
                  dataType:'json',
                  success: function(e) {
                    $('#username').html('Current username:'+e.current_username);
                    $('#output').html('Action:'+e.message);
                  },
                });                 
            }
        </script>
    </body>
</html>

process.php

<?php
    session_start();
    $output = array(
        'current_username'  => '',
        'message'           => '',
    );

    if (isset($_POST['username']) && trim($_POST['username']) != '') {
        if (!isset($_SESSION['prevUsername'])) {
            /*
            $stmt = $db->prepare('INSERT INTO Users (`username`) VALUES (?)');
            $stmt->bind_param('s', $_POST['username'])
            $stmt->execute();
            */

            $output['message'] = 'Tracked new username: '.$_POST['username'];
            $_SESSION['prevUsername'] = $_POST['username'];

        }else{
            /*
            $stmt = $db->query('UPDATE Users SET username = ? WHERE username = ?');
            $stmt->bind_param('s', $_POST['username'])
            $stmt->bind_param('s', $_SESSION['prevUsername'])
            */

            $output['message'] = 'Changed old username from '.$_SESSION['prevUsername']. ' to '.$_POST['username'];
            $_SESSION['prevUsername'] = $_POST['username'];
        }
    }else{
        $output['message'] = 'Nothing happend';
    }
    if (isset($_SESSION['prevUsername'])) $output['current_username'] = $_SESSION['prevUsername'];

    header('Content-Type: application/json');
    echo json_encode($output);