PHP无法显示更新的值

时间:2017-01-31 05:55:24

标签: php jquery mysql session

我正在尝试在showName div中显示更新后的值,但我的网站仅在注销并再次登录后显示更新后的值

  1. saveName按钮更新用户名。
  2. 在PHPMyAdmin users表中成功更新用户名。
  3. showName div仍显示旧用户名。即使我刷新页面。
  4. 的index.php

    <div id="showName">
    <?php
        if(isset($_SESSION['userId'])){
            echo $_SESSION['username']; }
    ?>
    </div>
    <div id="message"></div>
    <div> <input id="editName" name="editName" /> </div>
    
    <button id="saveName" type="submit" >Save</button>
    

    edit.php

    <?php
    ob_start();
    session_start();
    
    include_once('database.php');
    
    $validUser= $_SESSION["username"];
    
    if(isset($_POST['editName']))
    {   
        $username = $_POST["editName"];
    
        if ($username =="") {
            echo "Enter your full name.";
            return false;
        }else {
            $sql = "UPDATE users SET username='$username' WHERE username='$validUser'";
    
            if(mysqli_query($con, $sql)){
                echo "Successfully Updated.";
            } else{
                echo "Something went wrong"; }
        }
        return false;
    }
        ob_end_flush(); 
    ?>
    

    的script.php

    $("#saveName").click( function(e) {
        e.preventDefault();
        e.stopPropagation();
    
        $.post("edit.php",
        $("#editName").serializeArray(),
             function(info){ $("#message").html(info);
        });
    
    });
    

1 个答案:

答案 0 :(得分:0)

在数据库中更新后,您必须将新用户名置于会话中。 $_SESSION["username"] = $your_new_username

<? php
ob_start();
session_start();

include_once('database.php');

$validUser = $_SESSION["username"];

if (isset($_POST['editName'])) {
  $username = $_POST["editName"];

  if ($username == "") {
    echo "Enter your full name.";
    return false;
  } else {
    $sql = "UPDATE users SET username='$username' WHERE username='$validUser'";

    if (mysqli_query($con, $sql)) {
      echo "Successfully Updated.";
      $_SESSION["username"] = $username // Updating the new username to session
    } else {
      echo "Something went wrong";
    }
  }
  return false;
}
ob_end_flush(); ?>