douaoli5328 2016-10-12 00:36
浏览 100
已采纳

循环中的PDO循环 - 如何使其正确?

I'm shifting to PDO from MySql_ AND/OR MySqli_ and I need some advice on how to get the things right. (Learning Process). In this case I have to loop thru categories (links_cat) and return all the records responding to this category from another table.(links). Code i have is working, but sure can be improved. And I would like to do it as professional as I can (without making in to crazy too.. (: Just clean, solid and fast code. Thank you for your advice in advance.

<?php 

// Get Link Categories
$links_cat = $pdo->prepare("SELECT * FROM links_cat");

$links_categories = array();
if ($links_cat->execute()) {
    while ($row = $links_cat->fetch(PDO::FETCH_ASSOC)):
        $links_categories[] = $row;
        $link_cat_id = $row['id'];
        $link_cat_name = $row['name'];
        echo $link_cat_name . "<br/>";

        // Get Links in current Category

        $links = $pdo->prepare("SELECT * FROM links WHERE category = '$link_cat_id' ORDER BY name");
        $links->execute(); 

            while ($link_row = $links->fetch()):
            echo $link_name = $link_row['name']. "<br/>";
            endwhile;

    endwhile;
}

$pdo = null;  

?>    

UPDATE

I joined tables and return all results but i would like to list category only once, not every record.

<?php 
$links_cat = "SELECT links_cat.name AS linkcat, links.link AS linkname FROM links_cat INNER JOIN links ON links.category=links_cat.id";
foreach($pdo->query($links_cat) as $row) {  
echo $row['linkcat'] . "<br>";  
echo $row['linkname'] . "<br>";  
}  
?> 

Listing right now is like this:

Cat 1
     - L1
Cat 1
     - L2
Cat 2
     - L3
Cat 2
     - L4

I'm looking for listing like this:

Cat 1
 - L1
 - L2
Cat 2
 - L3
 - L4
  • 写回答

1条回答 默认 最新

  • donglu4633 2016-10-12 03:15
    关注

    Try changing your code like this

    // ensure record is ordered by category name
    $links_cat = "SELECT links_cat.name AS linkcat, links.link AS linkname FROM links_cat INNER JOIN links ON links.category=links_cat.id ORDER BY links_cat.name";
    
    $prevCat = '';
    foreach($pdo->query($links_cat) as $row) {  
        // if category name different from previous, show it
        if($row['linkcat'] != $prevCat) {
            echo $row['linkcat'] . "<br>";  
            $prevCat = $row['linkcat'];
        }
        echo $row['linkname'] . "<br>";  
    }
    

    SELECT N+1 issue is code issue where SELECT query is executed in a loop. If loop count is high, then it will degrade performance. It's called SELECT N+1 because query is executed N times in loop plus 1 for initial query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题