简体   繁体   English

如何从php会话中获取mysql user_id?

[英]How do I get mysql user_id from php session?

In my code I use $user_id = $_SESSION["USER_ID"]; 在我的代码中,我使用$ user_id = $ _SESSION [“USER_ID”]; to get the users id that is valid. 获取有效的用户ID。 If I use echo function in PHP it displays the correct id but when I try to use it in query it says it is undefined. 如果我在PHP中使用echo函数它会显示正确的id但是当我尝试在查询中使用它时它表示它是未定义的。

I am using XAMPP with: PHP 7.1.27 , 7.2.16 , 7.3.3 Apache 2.4.38 MariaDB 10.1.38 Perl 5.16.3 OpenSSL 1.0.2r (UNIX only) phpMyAdmin 4.8.5 我正在使用XAMPP:PHP 7.1.27,7.2.16,7.3.3 Apache 2.4.38 MariaDB 10.1.38 Perl 5.16.3 OpenSSL 1.0.2r(仅限UNIX)phpMyAdmin 4.8.5

$user_id = $_SESSION["USER_ID"];

// Funkcija prebere oglase iz baze in vrne polje objektov

function get_oglasi(){
    global $conn;
    $query = "SELECT * FROM ads WHERE user_id= echo '$user_id'; ";
    $res = $conn->query($query);
    $oglasi = array();
    while($oglas = $res->fetch_object()){
        array_push($oglasi, $oglas);
    }
    return $oglasi;
}

I expect the output of $user_id = 17 and I get error that it is undefined. 我期望$ user_id = 17的输出,并且我得到错误,它是未定义的。 But if I try <p>Opis: <?php echo $user_id;?></p> I get correct number. 但是,如果我尝试<p>Opis: <?php echo $user_id;?></p>我得到正确的号码。

You need to make $user_id as global global $user_id; 您需要将$ user_id设为全局全局$ user_id; because You are using in function and it is define outside function. 因为你在函数中使用它是定义外部函数。

或者将参数传递给函数然后你将获得函数函数get_oglasi($ id)中的id

In php you are not able read variable without Global declaring or send to function parameter. 在php中,如果没有全局声明或发送到函数参数,则无法读取变量。 Please set this session user_id like below code 请将此会话设置为user_id,如下面的代码所示

 $user_id = $_SESSION["USER_ID"];

 function get_oglasi(){

 $user_id=$GLOBALS['user_id'];

 global $conn;
 $query = "SELECT * FROM ads WHERE user_id='$user_id'; ";
 $res = $conn->query($query);
 $oglasi = array();
 while($oglas = $res->fetch_object()){
    array_push($oglasi, $oglas);
 }
return $oglasi;
}

Hopefully that will help you. 希望这会对你有所帮助。

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

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