简体   繁体   English

无法从 PHP 脚本中检索会话变量

[英]Can't retrieve session variable from PHP script

I have an ajax posting of a form so that I can return values from PHP exactly as it shows here: https://jonsuh.com/blog/jquery-ajax-call-to-php-script-with-json-return/ .我有一个表单的 ajax 发布,以便我可以完全按照此处显示的方式从 PHP 返回值: https : //jonsuh.com/blog/jquery-ajax-call-to-php-script-with-json-return/ . There's a slight difference though, my response.php script is like this:不过有一点不同,我的 response.php 脚本是这样的:

<?php
session_start();

$email = $_SESSION['email'];

?>

<?php    
if (is_ajax()) {
    if (isset($_POST["action"]) && !empty($_POST["action"])) { 
        $action = $_POST["action"];
        switch($action) { 
        case "test": test_function(); break;
        }
    }
}

function is_ajax() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function test_function(){
    $return = $_POST;
    $x = $return["Profile"];

    define('DB_NAME', 'STUDENTS');
    define('DB_USER', 'STUDENTS');
    define('DB_PASSWORD', 'PASSWORD');
    define('DB_HOST','HOST');

    $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);       
    $db_selected = mysql_select_db(DB_NAME, $link); 

    $sql = "UPDATE  `STUDENTS`.`Students` SET  `Fbprofile` =  '$x' WHERE  `Students`.`StudEmail` = '$email'  ";

    $return["json"] = json_encode($return);
    echo json_encode($return);
}
?>

As you can see, the only difference is that I'm updating an SQL database.如您所见,唯一的区别是我正在更新 SQL 数据库。 The problem is that I want to update the Fbprofile column where StudEmail equals the email session variable.问题是我想更新 StudEmail 等于电子邮件会话变量的 Fbprofile 列。 This session variable works perfectly in all other pages, but I can't seem to retrieve it in my response.php.这个会话变量在所有其他页面中都能完美运行,但我似乎无法在我的 response.php 中检索它。 What actually happens is that the SQL update works but only updates all rows that have no email value in them, so I'm guessing it's not reading the $email variable.实际发生的是 SQL 更新有效但只更新所有没有 email 值的行,所以我猜它没有读取 $email 变量。 Thank you very much for your help.非常感谢您的帮助。

It's a variable scope problem.这是一个可变范围的问题。 You set $email outside of test_function , so it's not visible inside the function.您在test_function之外设置$email ,因此它在函数内部不可见。 If you had error reporting enabled, you would have seen a notice about the undefined variable.如果您启用了错误报告,您会看到有关未定义变量的通知。

You should pass it as an argument to the function:您应该将它作为参数传递给函数:

    case "test": test_function($email); break;

... ...

function test_function($email) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM