2

I am trying to get a variable from session storage and use it in my PHP MySQL query, but it keeps returning no values.

My JavaScript to get variables from session storage:

var myEmail = sessionStorage.getItem('myEmail'); 

Assigning a JavaScript variable to a PHP variable:

<?php
       $emailAddress = "<script>document.write(myEmail);</script>";
?>

And once connected to the database:

<?php
       $query = mysql_query("SELECT * FROM myTable WHERE emailaddress='$emailAddress';
?>

Can anyone see any problems? When I output the result it is just blank. Just before I make the query I echoed the email address and it output fine. Not sure when I put it in the query it just returns nothing. If i change the $emailAddress in the query for "someone@gmail.com" for example it works fine, just not with the variable.

tux3
  • 7,171
  • 6
  • 39
  • 51
jord49
  • 542
  • 2
  • 17
  • 37
  • No it will never work, the PHP will be executed before the Javascript and `$emailAddress` will be always null. Thats why we have ajax. – Abhik Chakraborty Apr 18 '15 at 19:28
  • 1
    You need to understand that PHP script runs at server and it's result is an HTML rendered by browser which also executes some JS code in it. In your case you need to use PHP session to store data. – dfsq Apr 18 '15 at 19:28
  • Possible duplicate: http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php – odedta Apr 18 '15 at 19:28
  • The order is: PHP on server -> HTML on server -> HTML in the browser (including Javascript). Your localStorage variable is accessed on the last stage. You'll have to use POST (will cause need a refresh), or AJAX or Websockets. – Sidd Apr 18 '15 at 19:33
  • Thanks for the replies, will use an ajax request instead. – jord49 Apr 18 '15 at 19:33

0 Answers0