2013-05-05 82 views
0

我從前一頁作爲「namer」傳遞給頁眉的javascript變量。現在我也想在php的sql查詢中使用該變量。我怎麼去發送這個JavaScript變量作爲變量「名稱」在服務器端的PHP?在php sql查詢中將JavaScript變量傳遞給服務器端

<!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> 
+0

的可能重複[參考:爲什麼在我的JavaScript的PHP代碼無法正常工作( http://stackoverflow.com/questions/13840429/reference-why-does-the-php-code-in-my-javascript-not-work) – Quentin 2013-05-05 21:08:42

+1

您正在使用[an **過時的**數據庫API](http ://stackoverflow.com/q/12859942/19068)並應該使用一個[現代替代品](http://php.net/manual/en/mysqlinfo.api.choosing.php)。你也**易受[SQL注入攻擊](http://bobby-tables.com/)**,現代的API會使[防禦]更容易(http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)自己從。 – Quentin 2013-05-05 21:09:04

回答

0

一些簡單的jQuery的例子。如果它不是敏感數據,並且你能承受重載,只需使用一個GET變量。

客戶端(JavaScript)

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

服務器端(PHP)

if (isset($_GET['namer']) && !empty($_GET['namer'])){ 
    $namer = $_GET['namer']; 
    // Now sanitize data and use it on your SQL query 
}