使用wpdb的嵌套查询

时间:2012-10-19 16:57:17

标签: mysql wordpress foreach wpdb

我试图为循环中显示的每个<h3><?php echo $name; ?></h3>项目显示几行数据。

使用当前代码,每个项<h3><?php echo $name; ?></h3>只显示一行

我在我的functions.php文件中有这个      $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; ?>

因此循环显示标题,后跟几行记录,而不仅仅是一行。

<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 个答案:

答案 0 :(得分: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_name,其名称值为{{ 1}}名称字段和其他字段,(没有重复),因此您可以加入两个表,如

tbl1

另外请记住$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关键字,就像我在回答中所写的那样

Class Reference/wpdbsql join以及this one