2009-06-12 46 views
1

我有一個查詢,當我用「回聲」測試,效果很好:這個REGEXP迴應了一件事,但又進入了MySQL。爲什麼?

$url = "http://search.twitter.com/search.json?q=&ands=&phrase=&ors=&nots=RT%2C+%40&tag=andyasks&lang=all&from=amcafee&to=&ref=&near=&within=15&units=mi&since=&until=&rpp=50"; 
$contents = file_get_contents($url); 
$decode = json_decode($contents, true); 
foreach($decode['results'] as $current) { 
    if(preg_match("/\?/", "$current[text]")){ 
    echo $current[text]."<br />"; 
    } 
} 

但是,當我將其更改爲它創建一個數據庫,它失去了一個記錄:

$url = "http://search.twitter.com/search.json?q=&ands=&phrase=&ors=&nots=RT%2C+%40&tag=andyasks&lang=all&from=amcafee&to=&ref=&near=&within=15&units=mi&since=&until=&rpp=50"; 
    $contents = file_get_contents($url); 
    $decode = json_decode($contents, true); 
    foreach($decode['results'] as $current) { 
    $query = "INSERT IGNORE INTO andyasks (questions, date, user) VALUES ('$current[text]','$current[created_at]','Andy')"; 
    if(preg_match("/\?/", "$current[text]")){ 
    mysql_query($query); 
} 
} 

具體來說,它跳過的Tweet是「amcafee:#andyasks本月晚些時候在波士頓的Enterprise 2.0會議參與者應該怎麼做?#e2conf」。這是第一個回聲,但是在DB INSERT中被忽略了。有什麼想法嗎?

+0

strpos()會更簡單和更快速在這種情況下,例如if(strpos($ current ['text'],'?')!== false) – 2009-06-12 21:13:25

+0

今天要學習的另外一個PHP函數我想,謝謝你的提示;我很重要我沒有使用過90%的功能,所以我什至不知道在參考文獻中查找。謝謝。 – 2009-06-12 21:21:04

回答

4

有字符串中的一個單引號,它不會插入(我_emphasis_補充):

「amcafee:#andyasks應該怎樣的Enterprise 2.0會議出席者一定要做好,而他們** _」 _ **在本月晚些時候在波士頓?#e2conf「

裸露的單引號被MySQL解釋爲第一個值的結尾,並且將查詢的其餘部分變成亂碼。您需要轉義單引號(即將「他們」轉換爲「他們」,以便MySQL知道單引號是您的字符串的一部分。順便提一下,單引號技巧是SQL注入攻擊的主要來源, 。所以你應該時刻保持警惕單引號

如果您使用的是mysql擴展,你應該總是使用mysql_real_escape_string功能上的任何不可信數據:

$url = "http://search.twitter.com/search.jsonq=&ands=&phrase=&ors=&nots=RT%2C+%40&tag=andyasks&lang=all&from=amcafee&to=&ref=&near=&within=15&units=mi&since=&until=&rpp=50"; 
$contents = file_get_contents($url); 
$decode = json_decode($contents, true); 
foreach($decode['results'] as $current) 
{ 
    $query = "INSERT IGNORE INTO andyasks (questions, date, user) VALUES ('$current[text]','$current[created_at]','Andy')"; 
    if(preg_match("/\?/", "$current[text]")) 
    { 
    mysql_real_escape_string($query); 
    mysql_query($query); 
    } 
} 
0

PHP/MySQL的調試技巧

  1. 當你呼應了調試語句,請確保您查看HTML頁面的源看到什麼實際被髮送到MySQL。

  2. 在查看echo'd頁面的源代碼時,將SQL查詢直接複製並粘貼到mysql控制檯(如果使用的話,則爲phpMyAdmin)並查看會發生什麼情況。

  3. 考慮使用日誌函數而不是回顯mysql語句。這裏有一個腦死亡的記錄器可以使用


class BrainDeadLogger { 
    static public function log($output, $file='/tmp/test.txt') { 
     file_put_contents($file,"$output\n",FILE_APPEND); 
    } 
} 
BrainDeadLogger::log($sql); 

然後監視日誌的東西,如

tail -f /tmp/test.txt 

Unix命令行上。您可以下載Tail for Windows,這應該類似地工作。

相關問題