2014-01-29 26 views
0

,如果我有這樣http://www.mywebsite.com/page.php?q=Banana&NewYork,其中香蕉 水果類和紐約是我的MySQL數據庫城市類別中的HTTP GET方法的URL,我該怎麼處理與MySQL的要求 這樣在頁面.PHP會顯示特定的URL請求PHP MYSQL GET方法和兩類

php 
$q= ($_GET['q']); 
$q = htmlspecialchars($q); 
$q = mysql_real_escape_string($q); 

mysql 
$req = $db->prepare ('SELECT * FROM tab WHERE ...'); 
$req->execute(); 

感謝大家。

+1

你是什麼意思?您可以像使用$ _GET ['q']那樣獲得您的「水果」類別,而您的「城市」類別使用$ _GET ['c']如果您修復了URL中的錯誤並生成page.php?q = Banana&c = NewYork –

回答

2

如果您的URL如下所示:...page.php?fruit=Banana&city=NewYork您可以使用以下示例代碼。

此外,您應該使用準備的語句,而不是mysql_real_escape_string

<?php 

$fruit = $_GET['fruit']; 
$city = $_GET['city']; 

//mysql 
//Prepare the query and create a stmt 
$req = $db->prepare("SELECT * FROM table_name WHERE fruit = ? AND city = ?"); 

//$req contains now a prepared statement - binding the parameters 
//because at both "?" there are strings, there need to be "ss" 
//The value of $fruit will be placed at the first ? - $city will be placed at the second ? 
$req->bindParam("ss",$fruit,$city); 

//Execute the statement 
$req->execute(); 
?> 
+1

+1使用準備好的語句。不像@ user3052781由於缺乏安全性和可能的​​SQL注入,我投了票。 –

2

爲了節省自己的解析一個完整的查詢字符串,在URL中使用兩個參數,例如:

?fruit=Banana&city=NewYork 

然後可以使用$_GET['fruit']$_GET['city']檢索這些值。

然後,您需要將它們放入查詢前要正確消毒的投入,我看你正在使用mysql_real_escape_stringmysql_query但是這並不推薦,因爲在mysql_*功能棄用。

請使用準備好的語句來查看mysqli_*甚至更​​好。 SO上有許多可用的資源,並且您會在搜索引擎上找到更多資源。

2
<?php 
$fruit = (isset($_GET['fruit'])) ? $_GET['fruit'] : ''; 
$city = (isset($_GET['city'])) ? $_GET['fruit'] : ''; 

$fruit = htmlspecialchars($fruit); 
$fruit = mysql_real_escape_string($fruit); 

$city = htmlspecialchars($city); 
$city = mysql_real_escape_string($city); 

//mysql 
$req = $db->prepare("SELECT * FROM tab WHERE fruit = '".$fruit."' AND city = '".$city."'"); 
$req->execute(); 

但是URL查詢應該是http://www.mywebsite.com/page.php?fruit=Banana&city=NewYork

編輯:

在剛開始時,我檢查$ _GET水果和城市設置,如果是這樣,得到他們的價值觀,如果沒有把''或空字符串。

然後我通過htmlspecialchars和mysql_real_escape_string清理了url輸入。

然後我們準備一個查找水果和城市然後執行的sql語句。

+0

解釋你在做什麼,而不是向別人扔「工作代碼」。 – Ryan

-1

您的網址應該是這樣的page.php文件?水果= bannana &城市=紐約

之後,你必須得到這兩個可變像

<?php 

$fruits = $_GET['fruit']; 


$city = $_GET['city']; 

$query = mysql_query("SELECT * from tablename where fruits = '".$fruits."' and city = '".$city."'"); 

$res = mysql_fetch_array($query); 


?> 

希望它會幫助你:)

+0

使用此語法的可能的SQL注入! –