2012-01-16 2 views
1

테이블에서 데이터를 가져 와서 html 텍스트의 문자열을 바꾸는 데 문제가 있습니다. 테이블에서 마지막 4 개의 행을 검색 한 다음 str_replace를 사용하여 자동으로 href를 작성해야합니다. 하나의 열은 url이고, 하나는 제목이고, 하나는 설명입니다. 그런 다음 각 행에서 4 개의 개별 hrefs를 만듭니다. 내가 지금까지 가지고있는 것은 마지막 결과만을 위해 일할 것이다. 어떻게 4에 모두 적용 할 수 있습니까?테이블에서 str_replace로 행 검색

$query = "SELECT * FROM LINKS ORDER BY id DESC LIMIT 4"; 
if(!$result = mysql_query($query)){ 
    // query failed, handle the error here... 
    $errors[] = "A fatal error occurred and this page is non-functional at this time!"; 
    trigger_error("Query failed: $query<br /> Due to: " . mysql_error()); // application error 
} else { 
    // query worked 
    if(!mysql_num_rows($result)){ 
     // no matching rows 
     $main_content .= "No rows were found!\n"; 
    } else { 
     // query matched at least one row, use the results from the query here... 
     $row = mysql_fetch_assoc($result); 
     $title1 .= $row['title']; 
     $link1 .= $row['url']; 
    } 
} 
//string replace arrays 
$placeholders = array('LINK1','LINK2', 'LINK3','LINK4'); 
$replacevals = array($link1, $link2, $link3, $link4); 

//replace the areas of the template with the posted values 
$page = str_replace($placeholders,$replacevals,$template); 

나는 등 출력 $의 직책 2, $의 링크 2, $ TITLE3,

+0

어디에서'str_replace()'가 있고 HTML는 어디에 있습니까? – DaveRandom

+0

죄송합니다. str_replace를 포함하는 것을 잊었습니다. 나는 그것을 바닥에 더했다. –

답변

1

가장 쉬운 방법은 다음과 같이 뭔가를하는 것입니다 :

... 
// query worked 
if(!mysql_num_rows($result)){ 
    // no matching rows 
    $main_content .= "No rows were found!\n"; 
} 
else { 
    $urls_array = Array(); 
    // query matched at least one row, use the results from the query here... 
    while ($row = mysql_fetch_assoc($result)) 
    { 
    $urls_array[] = "<a href='" . $row['url'] . "'>" . $row['title'] . "</a>"; 
    } 
} 

그런 다음 당신이 $urls_array 변수로 설정 HTML 링크의 배열로 끝날.

+0

잘 작동합니다. 감사합니다! 그러나, 나는 나쁜 PHPer입니다. $ urls_array의 echo를 PHP 코드의 다른 곳에서 생성 된 HTML 페이지에 포함시켜야합니다. 그래서 str_replace를 사용하려고했습니다. 하지만 $ link1 = echo $ urls_array [1]는 작동하지 않습니다. –

+0

[foreach 루프를 사용하여 배열을 반복하는 방법] (http://php.net/manual/en/control-structures.foreach.php)에 대한 PHP 문서를 읽어보십시오. – Batkins

+0

Blah, 알아 냈습니다. 도와 줘서 고마워! –

0

사용을 mysql_fetch_assoc()와 루프 수 있도록하고 싶습니다. 전통적으로 while 루프. 당신이 시작해야

while ($row = mysql_fetch_assoc($result)) { 
    echo $row['title']; 
} 

:

다음은 PHP docs에서 파생 된 예입니다. StackOverflow에 오신 것을 환영합니다. 그렇게 할