2012-09-21 2 views
1

두 개의 다른 테이블 (두 개의 별도 쿼리 사용)에서 정보를 가져 와서 "뉴스 피드"를 내 사이트에 통합하려고합니다. 하나의 피드는 현재 뉴스 "$ newsfeed"를 가져오고 다른 하나는 "$ historyfeed"라는 역사 뉴스를 가져옵니다. 두 테이블 모두 개별적으로 유지해야합니다 (). 난 세트 번호 또는 행에 대한 임의의 순서로 이러한 쿼리를 배치하려고합니다. 예를 들어 5 가지 이야기를 나열하고 싶습니다. 역사와 뉴스는 무작위로 선택합니다.두 개의 서로 다른 테이블 쿼리 간 전환 PHP MySQL

수 있습니다 순서 : 역사, 뉴스, 역사, 역사, 역사

다음 방문 생산할 수 있습니다 뉴스, 신문, 새로운, 역사, 신문

이 부분이 작동하는 것 같다 괜찮습니다 ...

그러나 쿼리의 다음 행으로 이동할 수 없었습니다. 따라서 정확히 같은 뉴스 기사 다섯 개가 쿼리의 다음 행으로 이동하는 대신 생성됩니다.

//DB connection established earlier 
$newsfeed = mysql_query("SELECT * FROM newsfeed WHERE story_type='business'"); //News Story Query 
$row_newsfeed = mysql_fetch_assoc($newsfeed); 

$historyfeed = mysql_query("SELECT * FROM newsfeed WHERE story_type='business'"); //History Story Query 
$row_historyfeed = mysql_fetch_assoc($historyfeed); 

$storycount = 0; 
while ($storycount < 5) { 

$storytype = rand(1,2); //randomly select next story type 

switch ($storytype){ 
    case: "1" //if next story is a new story 
      storybubble($row_newsfeed); //function to echo newsfeed content 
      $storycount++; 
    break; 
    case: "2" //if next story is a history story 
      storybubble($row_historyfeed); //function to echo historyfeed content 
      $storycount++; 
    break; 
    default: 
      echo "Error"; 
} //switch statement 
} //story count while statement 

답변

1

당신은 $historyfeed$newsfeed에 상단에 변수 및 부하 이야기를 만들고, 아래 예제 코드 참조 그러나 루프에서 동일한 변수를 계속 사용합니다. 이것은 조금 더 잘 작동 할 것입니다 :

case: "1" //if next story is a new story 
     $row_newsfeed = mysql_fetch_assoc($newsfeed); 
     storybubble($row_newsfeed); //function to echo newsfeed content 
     $storycount++; 
break; 
case: "2" //if next story is a history story 
     $row_historyfeed = mysql_fetch_assoc($historyfeed); 
     storybubble($row_historyfeed); //function to echo historyfeed content 
     $storycount++; 

변수가 필요할 때 코드 시작 부분에 채워집니다.

+0

도움 주셔서 감사합니다. 귀하의 제안이 트릭을 완료했습니다! –

+0

@RichStreets - 하이비스커스의 대답을 살펴 보길 권합니다. 그것은 같은 논리이지만, 내 솔루션보다 더 우아하다고 생각한다. – andrewsi

1

mysql_fetch_assoc()은 결과의 한 행을 반환합니다.

다음 행을 반환하려면 mysql_fetch_assoc()을 다시 호출해야합니다.

그래서 당신은에 storybubble에 통화를 변경할 수 있습니다 :

storybubble(mysql_fetch_assoc($row_newsfeed)); 

그러나, 당신은 아마 행의 배열을 구축하고 그에서 끌어 더 나을 수 있습니다.

$newsfeed = array(); 
$historyfeed = array(); 
while($row = mysql_fetch_assoc($newsfeed)) { 
$newsfeed[] = $row; 
} 

while($row = mysql_fetch_assoc($historyfeed)) { 
$historyfeed[] = $row; 
} 

... 

switch($storytype) { 
case 1: 
storybubble(array_shift($newsfeed)); 
break; 
} 

... 
+0

+1 매우 깔끔한 해결책 – andrewsi

관련 문제