2011-03-21 92 views
1

有人可以教我如何清理查詢嗎?我是否應該淨化$ first_word?我如何清理下面的查詢?

$question_text = sanitize($_POST['question_text']); 

list($first_word) = explode(' ', $question_text); 

$qStuff=mysql_query("SELECT c.field_name,t.category_name, d.domain_name FROM category_fields c, taxonomy_category t, taxonomy_domain d WHERE c.category_id = t.category_id AND t.domain_id = d.domain_id AND c.field_name = '$first_word'"); 
+0

在這種情況下,「淨化」意味着什麼? – deceze 2011-03-21 05:36:39

+0

對PDO進行消毒以防止sql注入 – Abby 2011-03-21 05:37:26

回答

2

使用PDO和參數像這樣綁定:

$sql = "INSERT INTO table (field) VALUES (?)"; 
$sth = $dbh->prepare($sql); 
$sth->execute(array($value)); 
0

「消毒」 是不一定相同的 「SQL轉義」。要爲MySQL的SQL轉義值,該值使用mysql_real_escape_string你要投入查詢:

$first_word = current(explode(' ', $_POST['question_text'])); 

// sanitize $first_word here if you want to to remove certain things 

mysql_query("SELECT … '" . mysql_real_escape_string($first_word) . "'"); 
0

我建議使用的preg_match語句來限制字符類型。我也建議使用PHP PDO並準備SQL語句。我在手機上,或者我會張貼鏈接。

1

如果你想使用mysql_*功能,以保持,您必須使用mysql_real_escape_string()逃避你的字符串數據:

$first_word_escaped = mysql_real_escape_string($first_word); 
$qStuff=mysql_query("SELECT c.field_name,t.category_name, d.domain_name FROM category_fields c, taxonomy_category t, taxonomy_domain d 
    WHERE c.category_id = t.category_id 
      AND t.domain_id = d.domain_id 
      AND c.field_name = '$first_word_escaped'"); 


注:

:作爲 Overview of the mysqli extension (報價)

什麼是PHP的MySQL擴展?

這是原來的擴展 設計,讓你開發PHP應用 與一個 MySQL數據庫進行交互。
mysql擴展 提供了一個程序接口,並且是 ,旨在僅用於版本低於4.1.3的MySQL 版本。
這個 擴展可以使用版本 MySQL 4.1.3或更新版本,但不是全部的 最新的MySQL服務器功能將 可用。

注:如果你正在使用MySQL版本4.1.3或更高版本,強烈 建議您使用 的mysqli擴展來代替。


另一解決方案是停止使用mysql_* familly的功能,並切換到eiter mysqliPDO,使用預處理語句 - 它們是不是由mysql_*支持新功能之一:

這些,你將不得不逃避你的數據:它會自動綁定它們的值時完成。

+0

+1,但值得更多關注:) – Kevin 2011-03-21 05:55:34

0

使用PDO等現代數據庫功能,並使用參數化查詢。