【问题标题】:Session variable not Updating even after including session_start()会话变量即使在包含 session_start() 后也不会更新
【发布时间】:2018-04-22 03:10:24
【问题描述】:

我有一个名为 train_detail.php 的页面。我在那个页面上有一个表,它是使用 SQL 制作的,并且有 train_id 作为它的列属性之一。在每一行的末尾都有一个名为 check_availability 的按钮。单击此按钮时,将打开一个新模式。它将行值(train_id)传递给模态。我使用 JS 通过 post 方法将值传递到页面 helpe.php 来做到这一点。现在,我已经创建了 $_SESSION 变量并将 $_POST 变量的值传递给了 SESSION 变量。但问题是会话变量无法更新其值。请帮帮我。

train_detail.php-

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <title>Home</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <style>
    .header{
        width: 70%;
    }
    .content {
        width: 70%;
    }
    <?php  
    session_start();
    $db = mysqli_connect('localhost', 'root', '', 'registration');
    $Source =$_SESSION['Source'];
    $Destination = $_SESSION['Destination'];
    $query = "SELECT * FROM train_details WHERE train_source='$Source' AND train_destination='$Destination'";
    $results = mysqli_query($db, $query);
?>

</style>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: center;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
<style>
#myDIV {
    width: 100%;
    padding: 50px 0;
    text-align: center;
    background-color: lightblue;
    margin-top:20px;
}
.hidden{
       display:none;
    }
</style>
</head>
<body>
    <div class="header">
        <h2>Train details</h2>
    </div>

    <div class="content">


            <table>
        <tr>
            <th>Train no.</th>
            <th>Train name</th>
            <th>Train departure</th>
            <th>Train arrival</th>
            <th></th>

        </tr>
        <script>
        function myFunction() {

}
        </script>
        <tbody>
        <!--Use a while loop to make a table row for every DB row-->
            <?php while( $row = mysqli_fetch_array($results)) : ?>
        <tr>
            <!--Each table column is echoed in to a td cell-->
            <td><?php echo $row["train_id"]; ?></td>
            <td><?php echo $row["train_name"]; ?></a></td>
            <td><?php echo $row["train_departure"]; ?></td>
            <td><?php echo $row["train_arrival"]; ?></td>
            <td>
                <button type="button" id="availability"  class=" open-AddBookDialog btn btn-info btn-lg" data-toggle="modal" data-id="<?php echo $row["train_id"]; ?>"
                href="#addBookDialog">Check availability</button>
            </td>

        </tr>
        <?php endwhile ?>
        </tbody>
</table>    

        <!--modal-->
        <div class="modal fade" id="addBookDialog" role="dialog">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Modal Header</h4>
                    </div>
                    <div class="modal-body">


                    <p><?php echo $_SESSION['var_train2']  ?></p>
                    <input type="text" name="bookId" id="bookId" value=""/>

                    <div id="train">
                    </div>
                    <table style="width: 100%">
                        <tr>
                            <th>Date</th>
                            <?php
                            $query = "SELECT * FROM train_status WHERE 1";
                            $results = mysqli_query($db, $query);
                            ?>
                            <?php while( $row = mysqli_fetch_array($results)) : ?>
                            <th><?php echo $row["train_date"]; ?></th>
                            <?php endwhile ?>       
                        </tr>
                        <tr>
                            <th>availability</th>
                            <?php
                            $query = "SELECT * FROM train_status WHERE 1";
                            $results = mysqli_query($db, $query);
                            ?>
                            <?php while( $row = mysqli_fetch_array($results)) : ?>
                            <th><?php echo $row["availability"]; ?><br>
                            <a href="login.php?logout='1'" style="color: blue;">book now</a></th>
                            <?php endwhile ?>
                        </tr>

                    </table>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" onclick="myFunction()" data-dismiss="modal">Close</button>
                        <script>
                        function myFunction() {
                        location.reload();

                        }
                        </script>
                    </div>
                </div>
            </div>
        </div>

        <script type="text/javascript">
            $(document).on("click", ".open-AddBookDialog", function () {
            var myBookId = $(this).data('id');
            $(".modal-body #bookId").val( myBookId );

            $.ajax({
            type: 'post', // the method (could be GET btw)
            url: 'helper.php', // The file where my php code is
            data: {
            'test': myBookId // all variables i want to pass. In this case, only one.
            },
            success: function(data) { // in case of success get the output, i named data
            alert(data); // do something with the output, like an alert
            }
            });
            }); 

        </script>   

            <p> <a href="login.php?logout='1'" style="color: red;">logout</a> </p>


    </div>

</body>
</html>

helper.php-

<?php
    session_start();
    if(isset($_POST['test'])) { //if i have this post

    echo $_POST['test']+1; // print it   
    $_SESSION["var_train2"] =$_POST['test'];
    echo $_SESSION['var_train2'];

}
?>

【问题讨论】:

  • 你在尝试做 $_SESSION["var_train2"] =$_POST['test'] +1; ?
  • echo $_SESSION['var_train2'] 给你输出了吗?
  • 是的,它给了我一个输出。但是当我点击其他按钮时,这并没有改变。

标签: php ajax session


【解决方案1】:

您正在混合两个编程层:

  1. PHP 层在服务器 任何内容传送到客户端之前进行处理。

  2. JS 层在客户端上进行处理,服务器完成处理并将内容交付给客户端。

因此,客户端(JS)无法读取任何服务器变量的内容,包括“$_SESSION”变量。 模态对话框显示为引导 (BS) 框架的一部分通过 JS(隐藏在 BS 代码的深处)。它完全使用客户端 JS 代码显示,没有额外的服务器往返。所以这一行的PHP:

<p><?php echo $_SESSION['var_train2']  ?></p>

服务器端处理,用户点击任何按钮之前,甚至在客户端甚至接收到任何 HTML 之前。因此,假设会话一开始是空的,呈现的 HTML 代码如下所示:

<p></p>

检查浏览器的原生 HTML 显示(查看源代码命令)以进行验证。这就是原因,当您单击按钮时,您在对话框中看不到任何值。

现在,当您的 客户端 按钮被点击时,您可以在 AJAX 调用中调用帮助脚本。这将设置会话变量中按钮的 ID。会发生什么:

  1. 按下按钮会触发客户端 JS 脚本,该脚本不能设置任何$_SERVER var。

  2. JS 脚本运行 AJAX 调用,请求服务器端帮助脚本。

  3. 服务器端帮助脚本在服务器上执行,设置$_SESSION var,内容由AJAX调用发布。

    李>
  4. 服务器端帮助脚本终止,$_SESSION var 现在包含新值。

  5. 客户端引导部分显示模态对话框,其中仍包含原始空行:

&lt;p&gt;&lt;/p&gt;

现在您获得了交易的一部分,您已经设置了 $_SERVER 变量。但它不会在没有重新加载的情况下显示客户端。要在客户端上显示代码,您有多种可能性:

  1. 将模态对话框放在一个单独的 php 文件 (dialog.php) 中,然后在浏览器弹出窗口或浏览器主窗口中打开该文件,替换当前内容。将火车 ID 发布到该 dialog.php 并从数据库中读取您需要的所有内容。这里不需要任何 ajax 或任何 BS 模态对话框。

  2. 使用当前的 BS 模态对话框,但使用 JS 填充其内容。

案例1我就不细说了,只讲案例2:

更改上面的行以包含一个 ID:

&lt;p id="myID"&gt;&lt;/p&gt;

在onclick函数中,除了现有代码外,还使用JQuery来设置&lt;p id="myID"&gt;&lt;/p&gt;标签的内容:

$(".modal-body #bookId").val( myBookId );
$("#myID").text(myBookId); // new

现在对话框应该显示相应按钮的 ID。如果您希望通过 AJAX 从服务器加载更多数据并显示在对话框中,您可以考虑使用像 AngularJS 这样的框架来为您完成这项工作。那里的学习曲线当然要陡峭一些。

另一个(完全不同的)问题可能是您构建查询的行中可能存在 SQL 注入错误:

$query = "SELECT * FROM train_details WHERE train_source='$Source' AND train_destination='$Destination'";

这看起来很容易受到 SQL 注入错误的影响。如果例如有人将源设置为恶意的,它可能会完全改变查询的含义。您应该使用mysqli_real_escape_string 封装您的值,或者首先使用prepared statement

【讨论】:

  • 很抱歉,您是在告诉我使用 JS 创建一种会话变量吗?如果可能的话,请您给我一个关于正确代码是什么样子的 sn-p?
  • 不,您正在混合 2 层。如您所说,您不能在 JS 中创建会话变量,也不能在 JS 中读取它们。您必须分别查看两个层,php 和 JS。我将尝试在答案中详细说明。
猜你喜欢
  • 1970-01-01
  • 2019-02-20
  • 2020-01-16
  • 2011-06-05
  • 2012-04-15
  • 2014-05-25
  • 2022-01-04
  • 2013-10-19
  • 1970-01-01
相关资源
最近更新 更多