2014-10-05 51 views
0

我的一些行在該字段中具有「,」逗號作爲初始字符。所以我需要循環,檢查每一行是否有最初的commma,如果有,則刪除它,然後更新該行。使用mysql_fetch_assoc並更新每條記錄

我正在運行下面的代碼,當更新被調用時,這段代碼似乎進入無限循環。

當我只是在最後迴應結果時,瀏覽器中的所有內容都很正常。但是在echo下執行更新行時,似乎每個記錄都會填充「標籤」列中的單個數據,而不是僅包含我正在刪除的初始commma的行。

很想幫助:)

$query = mysql_query("SELECT Tags FROM products") 
    or die (mysql_error()); 

while ($row = mysql_fetch_assoc($query)) 
{ 
    $str = $row['Tags']; 
    $initial = substr($str,0,1); 

if ($initial = ",") { 
     $str = (ltrim($str, ',')); 
    } 

    echo "result: " .$str . "<br/>"; 
    $result = "UPDATE products SET Tags = '" .$str ."'"; 
    mysql_query($result); 
} 

謝謝。

回答

0

你是if()語句中有錯誤。
您使用一個平等的:

if($initial = ",") { 

} 

相反的兩個用於實際的比較:

if($initial == ",") { 

} 
2

您應該通過特定的行ID你是要修改的一個,通過使用WHERE條款:

$query = mysql_query("SELECT Tags FROM products") 
    or die (mysql_error()); 

while ($row = mysql_fetch_assoc($query)) { 
    $str = $row['Tags']; 
    $initial = substr($str,0,1); 

    if ($initial == ",") { 
     // == not = 
     $str = (ltrim($str, ',')); 
    } 

    $id = $row['id']; 
    echo "result: " .$str . "<br/>"; 
    $result = "UPDATE products SET Tags = '$str' WHERE id = $id"; 
    mysql_query($result); 
} 

順便說一句,如果可能的話親切地換到更好的延伸範圍的mysqli或PDO來代替。

+1

現在,這是一個更好的描述:)謝謝弗雷德 – Ghost 2014-10-05 04:22:10

+0

不客氣。 – 2014-10-05 04:23:14

+0

謝謝。我在瀏覽器中收到錯誤 - 「未定義的索引:ID」。那是因爲數組是聯想的嗎? – Kailas 2014-10-05 05:04:34

0

以下是完整的代碼。謝謝大家。

$query = mysql_query("SELECT ProductID, Tags FROM products") 
    or die (mysql_error()); 

while ($row = mysql_fetch_assoc($query)) { 
    $str = $row['Tags']; 
    $initial = substr($str,0,1); 

    if ($initial == ",") { 
     $str = (ltrim($str, ',')); 

     $id = $row['ProductID']; 
     //echo $id . " "; 
     //echo $str . "<br/>"; 
    $result = "UPDATE products SET Tags = '$str' WHERE ProductID = $id"; 
     echo $result ."<br>"; 
     mysql_query($result); 
    } 
} 

非常感謝您的幫助。我也會更新到mysqlli。