2011-11-17 89 views
1

我目前有一個17列寬的表,有30個記錄。更新MySQL中的所有記錄

基本上,它是從另一個網站的表中,我刮,然後插入MySQL表。

$html = str_get_html($newHTML); // get the HTML  
     $tdContents = ""; // declare variable 
     $rowArray = array(); // declare array for records 
     for ($j = 0; $j < 510; $j++) // loop through each TD element, 17 columns by 30 records so 510 
     { 
      $f = $html->find("td",$j); // get the td elements from the html 
      $tdContents = $f->innertext; // get the text inside the td 
      $rowArray[] = $tdContents; // store that text inside the array 

      if ($j == 16 || $j == 33 || $j == 50 || $j == 67 || $j == 84 || $j == 101 || $j == 118 || $j == 135 || $j == 152 || $j == 169 || $j == 186 || $j == 203 || $j == 220 || $j == 237 || $j == 254 || $j == 271 || $j == 288 || $j == 305 || $j == 322 || $j == 339 || $j == 356 || $j == 373 || $j == 390 || $j == 407 || $j == 424 || $j == 441 || $j == 458 || $j == 475 || $j == 492 || $j == 509) // every 17 td elements 
      { 
       $comma_separated = implode("','", $rowArray); // seperate the array contents with commas and apostrophes, set up for mysql 
       $comma_separated = "'" . $comma_separated . "'"; // add apostrophes to beginning and end of the string 
       $result = mysql_query("INSERT INTO standings_20112012 VALUES (".$comma_separated.")"); // insert the data into mysql 
       $rowArray = array(); // clear the array, for the next record 

      } 
     } 

評論應該說明很好。這會生成一張表格17 x 30,包含我需要的所有信息。如果我再次運行它,它會插入另外30條記錄,這是不好的。我只想更新/覆蓋等已經創建的表。所以表中只能有30條記錄。然而,我很難過。

任何幫助?

+2

首先'if($ j == 16 || $ j == 33 ...)'是'if(($ j + 1)%17 == 0)'...... – Peter

+0

每次插入,檢查記錄是否已經存在。如果有,請檢查是否需要更新。如果不存在,則插入。 – xbonez

+0

mysql有一個'替換命令' – ajreal

回答

2

爲您的數據集添加一個唯一的主鍵。然後將你的mysql查詢改爲INSERT IGNORE,它會拋出重複項。或者,如果您需要更新表中已有的內容,也可以使用ON DUPLICATE UPDATE

+1

'ON DUPLICATE KEY'是基於帖子標題的路線。鏈接到語法對於OP來說可能是有用的http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html –

+0

會刪除表格,然後插入信息工作嗎? 也,我不知道我將設置爲主鍵的字段。 – jsquadrilla

+0

剛剛測試過,它的工作原理。我不確定它有多高效,但現在沒問題。有一個字段「等級」是1-30,是唯一的。如果我將其設置爲PK,那麼我需要在代碼中更改哪些內容? – jsquadrilla