2012-10-19 2 views
0

루프에 나타나는 각 <h3><?php echo $name; ?></h3> 항목에 대한 몇 줄의 데이터를 표시하려고합니다. 현재 코드와wpdb를 사용하는 중첩 쿼리

는 단지 $newdb = new wpdb('login', 'pass', 'db', 'host');

<?php $result=$newdb->get_results('select tbl1.name, tbl2.col1, tbl2.col2, tbl2.col3 from tbl1, tbl2 where tbl1.name=tbl2.tbl1_name'); 
$names=array(); 
foreach($result as $row): ?> 
<?php $names[$row->name][]=$row; 
endforeach; ?> 
<?php foreach($names as $name=>$info): ?> 

    <h3><?php echo $name; ?></h3> 
    <table> 
     <tr><th>col1</th><th>col2</th><th>col3</th></tr> 
     <?php foreach($info as $n):?>  
     <tr> 
      <td><?php echo $n->col1; ?></td> 
      <td><?php echo $n->col2; ?></td> 
      <td><?php echo $n->col3; ?></td>  
     </tr> 
     <?php endforeach; ?> 
    </table>  
<?php endforeach; ?> 

그래서 루프는 몇 행 다음에 제목을 표시 <h3><?php echo $name; ?></h3>

내가 내 functions.php 파일이있는 각 항목에 대해 하나 개의 행을 보여줍니다 레코드가 아니라 하나.

<h2>Name</h2> 
<table> 
<tr><th>col1</th><th>col2</th><th>col3</th></tr> 
     col1-value1 col2-value1 col3-value1 
     col1-value2 col1-value2 col1-value2 
     etc. 
</table> 

<h2>Name</h2> 
<table> 
<tr><th>col1</th><th>col2</th><th>col3</th></tr> 
     col1-value1 col2-value1 col3-value1 
     col1-value2 col1-value2 col1-value2 
     etc. 
</table> 

<h2>Name</h2> 
<table> 
<tr><th>col1</th><th>col2</th><th>col3</th></tr> 
     col1-value1 col2-value1 col3-value1 
     col1-value2 col2-value2 col3-value2 
     etc. 
</table> 
.....` 

답변

1

그것은 당신의 아이디어를 사용 가능하지만

global $wpdb; 
$result=$wpdb->get_results('select a.col, b.col1, b.col2, b.col3 from a,b where a.col=b.col5'); 

당신이 tbl1 테이블이 있다고 가정처럼 당신은 하나의 쿼리를 사용하여이 작업을 수행 할 수 있으며, 그것은 name 필드와 tbl2 테이블을 가지고 있으며, 그것은 예를 들어 필드가 이름이 tbl1 인 이름의 값이 tbl1_name이고 이름 필드와 다른 필드가 중복되지 않으므로 두 테이블에 모두 가입 할 수 있습니다.

$result=$wpdb->get_results('select tbl1.name, tbl2.col1, tbl2.col2, tbl2.col3 from tbl1, tbl2 where tbl1.name=tbl2.tbl1_name'); 
$names=array(); 
foreach($result as $row): ?> 
    $names[$row->name][]=$row; 
<?php endforeach; ?> 
foreach($names as $name=>$info): 
    echo $name; 
    ?><table><?php 
    foreach($info as $n): 
    ?> 
      <tr> 
       <td><?php echo $n->col1; ?></td> 
       <td><?php echo $n->col2; ?></td> 
       <td><?php echo $n->col3; ?></td> 
      </tr> 
    <?php 
    <?php endforeach; ?> 
    ?></table><?php 
<?php endforeach; ?> 

또한 $wpdb은 전체 개체이며 템플릿 파일을 통해 사용할 수 있으므로 new을 사용하여 instanse를 ​​만들 필요가 없습니다. 내 대답에 쓴 것처럼 global 키워드 만 사용하십시오.

Class Reference/wpdbsql jointhis one.

+0

귀하의 의견을 보내 주셔서 감사합니다. 귀하의 코드는 피곤하지만 테이블 1 (tbl1.name)의 각 이름 입력에 대해 하나의 행만 반환합니다. 각 이름 항목은 foreach 루프에 의해 반환되는 html 테이블의 몇 행을 가질 것이며 현재는 하나의 행만 표시합니다. 두 개의 쿼리가 있어야한다고 가정합니다. – stemie

+0

@ user1515699, 업데이트 된 답변을 확인하십시오. –

+0

감사합니다. Ive가 내 질문에 대한 답변을 업데이트했습니다 (팁 주셔서 감사합니다). 문제는 두 번째 마지막 foreach (코드 18 줄)에 대해 '예기치 않은 T_ENDFOREACH'가 발생한다는 것입니다. – stemie