0

I have a PHP file getting data from my SQL database and I am trying to set and get two session variables like $_SESSION['fname'] and $_SESSION['userID'] by $theFName and $theId.

       $email = $_POST['email'];
       $pass  = $_POST['pass'];
       $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);                
       $sql = "SELECT id, email, fname, lname, type FROM users WHERE `email`=? AND `pass`=?";              
       $stmt = $conn->prepare($sql);
       $stmt->bind_param('ss', $email,$pass);
       $stmt->execute();
       $stmt->bind_result($theId,$theEmail,$theFName,$theLname,$theType);
       if ($stmt->fetch()) {
            echo 'true';
            $_SESSION['LOGIN_STATUS'] = true;
            $_SESSION['fname'] = $theFName;
            $_SESSION['userID'] = $theId;
       } else {
            echo 'false';
        }

in JavaScript file I have

 <script>  
  var tok = "var UID = "<?php echo $_SESSION['userID']; ?>"; 
  console.log("The Id is " + UID)
</script>  

but I am getting empty string!

can you please let me know what I am doing wrong?

Behseini
  • 6,066
  • 23
  • 78
  • 125

1 Answers1

0

I'm not quite sure I understand what you are trying to do in the JS file, but it is not valid JS in any case - the quotes don't match and it seems like you are trying to do an assignment inside a string.

I think what you are looking for is something more along the lines of this:

<script>  
  var UID = "<?php echo $_SESSION['userID']; ?>"; 
  console.log("The Id is " + UID)
</script> 

However, please note that dynamically generating JS files using PHP is likely not the best way to go about this. Check out this SO answer on the various methods you can use to pass variables from PHP to JS, along with their various pros and cons.

Community
  • 1
  • 1
tbrisker
  • 15,518
  • 1
  • 16
  • 17