简体   繁体   中英

How do I get mysql user_id from php session?

In my code I use $user_id = $_SESSION["USER_ID"]; to get the users id that is valid. 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.

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

$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. But if I try <p>Opis: <?php echo $user_id;?></p> I get correct number.

You need to make $user_id as global global $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. Please set this session user_id like below code

 $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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