2014-10-05 1 views
0

일부 행의 필드에 ","쉼표가 첫 문자로 포함되어 있습니다. 그래서 루프를 통해 각 행에 초기 쉼표가 있는지 확인하고 제거한 경우 제거하고 행을 업데이트해야합니다.mysql_fetch_assoc 사용 및 각 레코드 업데이트

다음 코드를 실행하면 업데이트가 호출 될 때 무한 루프가되는 것 같습니다.

결과가 끝날 때마다 브라우저에서 모든 것이 정상적으로 보입니다. 그러나 에코 아래의 업데이트 라인을 실행하면 마치 내가 제거하고있는 초기 쉼표가있는 행 대신 모든 레코드에 대해 "태그"열의 단일 데이터가 채워지는 것처럼 보입니다.

도움 :

$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

이제 더 좋은 설명입니다 :) 감사합니다. Fred – Ghost

+0

여러분, 환영합니다. –

+0

감사합니다. 브라우저에 "Undefined index : id"오류가 나타납니다. 배열이 연관성이 있기 때문입니까? – Kailas

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로 또한 새롭게 할 것이다.