2011-04-27 36 views
-3

我已經保存爲example3.php下面的腳本(從一個大的腳本拍攝):傳遞JavaScript變量到PHP,使MySQL查詢

<script type="text/javascript"> 
var layer; 

//where layer is a table like 
------------------------------------ 
BUSNAME  + Category + 
------------------------------------ 
200 Bay  + Restaurant + 
201 Bay  + Bank   + 
202 Bay  + School  + 
203 Bay  + Restaurant + 
204 Bay  + School  + 
205 Bay  + Restaurant + 
206 Bay  + Restaurant + 
207 Bay  + School  + 
208 Bay  + Restaurant + 
209 Bay  + Restaurant + 
------------------------------------ 

window.location.href = "example3.php?layer="+ layer; 

<?php 
    //Make a MySQL Connection 
    $query = "SELECT Category, COUNT(BUSNAME) 
    FROM ".$_GET['layer']." GROUP BY Category"; 
    $result = mysql_query($query) or die(mysql_error()); 
    //Print out result 
    while($row = mysql_fetch_array($result)){ 
    echo "There are ".$row['COUNT(BUSNAME)']. " " .$row['Category']. "items."; 
    echo "<br/>"; 
    } 
?> 

</script> 

不要沒有,爲什麼它不工作。任何建議,必須感激。

+4

[SQL注入警報!](http://unixwiz.net/techtips/sql-injection.html) – BalusC 2011-04-27 21:30:49

+0

爲圖層變量分配一個值.. – 2011-04-27 21:37:24

+0

@teresko和David,來吧,不要點它告訴那個人如何解決它! – Johan 2011-04-27 21:53:54

回答

0

正如Balus指出的,注意SQL注入。當你到達php頁面時,$_GET['layer']等於什麼?

你的javascript變量等於什麼嗎? var layer = "layer

「layer」是數據庫中表的實際名稱。

-1

編輯

在此背景下mysql_real_escape_string()不起作用。

$layer = mysql_real_escape_string($_GET['layer']); 
$query = "SELECT Category, COUNT(BUSNAME) 
FROM `".$layer."` GROUP BY Category"; <<-- this doesn't work. 

因爲mysql_real_escape_string不逃避反引號`

有了值它的工作

你需要你$_GET拿到雖然mysql_real_escape_string運行每個值()。 (或使用PDO的)
除此之外,您輸入查詢的每個值都需要用單引號'括起來。

$value = mysql_real_escape_string($_GET['fieldname']); 
$query = "SELECT * FROM test WHERE f1 = '".$value."'"; <<-- this works 
             ^  ^

鏈接:
SQL注入攻擊:How does the SQL injection from the "Bobby Tables" XKCD comic work?
PDO的:mysqli or PDO - what are the pros and cons?

會我找到一個解決您的特定的SQL注入問題立即更新。

如果你有動力表名
+0

你碰巧使用過PDO嗎? – 2011-04-27 22:26:56

+0

是的,但我不是一個PHP的人。我是一個delphi程序員,Delphi是強類型的,所以插入整數我有時會作爲'query1.SQL.text:='選擇一個FROM b WHERE a ='+ IntToStr(i);'。如果我把字符串放進去,我總是執行'query1.ParamByName('x')。AsString:= MyString;' – Johan 2011-04-27 22:30:34

+4

評論是: - 無益 - 無禮 - 不正確 - 不完整的僅舉幾例。 – Johan 2011-04-27 22:40:23

4

你的數據庫設計是錯誤

爲你的腳本,它只是沒有任何意義。

在2部分:JS頁面和PHP頁面。並調用這個PHP頁面window.location.href

1

我建議在客戶端(在JS)的JSON編碼表。使用POST發送它,然後在服務器端對其進行解碼(使用PHP)。

大多數流行的JS庫都具有JSON編碼功能,PHP功能被稱爲json_decode