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.
3
Answers
You need to make $user_id as global global $user_id; because You are using in function and it is define outside function.
Or pass a parameter to a function then you will get the id inside the function
function get_oglasi($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
Hopefully that will help you.