0

I have a javascript variable from a previous page that is passed to the header as "namer". Now I also want to use that variable in a sql query in php. How do I go about sending this javascript variable to php on the server side as the variable "namer"?

<!DOCTYPE html>
<html>
    <head> 
        <title>My Page</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
        <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js">    </script>
    </head>
    <body>
        <script>
        $( document ).ready(function() {
                   var namer = sessionStorage.getItem("namer");
                   $('h1').text(namer)
            });
</script>                              
<div data-role="page" class="div1">            
            <div data-role="header"> 
        <h1>"namer"</h1> 
                </div>
        <div data-role="content">  
                <?php
                $link = mysql_connect("xxxx", "xxxx", "xxxx") OR DIE ("Unable to connect to database! Please try again later.");
                mysql_select_db("abxusername");
                $query = "SELECT class FROM Antibiotics WHERE name="."namer".";";
                echo $query;
                echo mysql_query($query);
                ?>
            </div>
        </div>
    </body>
</html>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user1518003
  • 321
  • 1
  • 7
  • 18
  • possible duplicate of [Reference: Why does the PHP code in my Javascript not work?](http://stackoverflow.com/questions/13840429/reference-why-does-the-php-code-in-my-javascript-not-work) – Quentin May 05 '13 at 21:08
  • 1
    You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin May 05 '13 at 21:09

1 Answers1

0

If it's not sensitive data and you can afford a reload, just use a GET variable.

client side (javascript)

document.location.href = "?namer=" + namer

Server side (PHP)

if (isset($_GET['namer']) && !empty($_GET['namer'])){
  $namer = $_GET['namer'];
  // Now sanitize data and use it on your SQL query
}
NiloVelez
  • 3,611
  • 1
  • 22
  • 30