0

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.

AnB
  • 7
  • 3
  • 1
    `$user_id` doesn't exist within `get_oglasi()`. See [Variable scope](https://www.php.net/manual/en/language.variables.scope.php). – Jeto Mar 30 '19 at 11:03
  • Thank you so much! I don't know what I was doing there... You resolved my issue. – AnB Mar 30 '19 at 11:10
  • 1
    Possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Progman Mar 30 '19 at 11:11

3 Answers3

0

You need to make $user_id as global global $user_id; because You are using in function and it is define outside function.

0

Or pass a parameter to a function then you will get the id inside the function function get_oglasi($id)

0

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.

Akbor
  • 1,280
  • 1
  • 9
  • 11